I have a variables.tf file which contains all the project variables and im trying to fetch a variable values using PowerShell.
variables.tf
variable "products" {
default = [
"Product-1",
"Product-2",
"Product-3",
"Product-4"
]
}
variable "product_unified_container" {
default = [
"cont-data",
"cont-data-2"
]
}
variable "location" {
default = "westeurope"
}
Using PowerShell i need to be able to fetch the variable values for any variable I want.
Example : the command should give me a array of all the products variables in variables.tf if it has multiple values.
write-host $product_list
Product-1
Product-2
Product-3
Product-4
if the variable has one value then it should give me that value like "location" variable.
write-host $deployed_location
westeurope
I was able to solve this by below approach hope this will help someone with similar requirement. Following Command will fetch any variable values present in variables.tf file, in this case variable "products" and assign it to another array variable.
$product_list = (Get-Content "variables.tf" -Raw) | Foreach-Object {
$_ -replace '(?s)^.*products', '' `
-replace '(?s)variable.+' `
-replace '[\[\],"{}]+' `
-replace ("default =","") | Where { $_ -ne "" } | ForEach { $_.Replace(" ","") } | Out-String | ForEach-Object { $_.Trim() }
}
foreach ( $Each_Product in $product_list.Split("`n")) {
write-host "Each Product Name : "$Each_Product
}
Output :
Each Product Name : Product-1
Each Product Name : Product-2
Each Product Name : Product-3
Each Product Name : Product-4