'How to Extract the variable values from terraform variables.tf file using PowerShell commands

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



Solution 1:[1]

I was going through a similar problem so, I can share a way using which you can extract the values. The problem is it is easy to extract and manipulate values in a json or other format but in tf files it is not the same. So, I have basically used a workaround where I have to set the given file in a structure that the values are filled in one single line So, variables.tf will look

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"
}

Next comes the PS code to extract the values of variables-

$paramsArray = @()
[system.array]$params = Select-String -Path "variables.tf" -Pattern "default =" -SimpleMatch
if (!([string]::IsNullOrEmpty($Params)))
        {
            [system.array]$paramsStrings =  $params -split {$_ -eq "="}

            foreach ($paramString in $paramsStrings)
            {
             
                if (($paramString -match "TF-Template") -or ($paramString -match "tf:"))
                    {
                       #Write-Output $paramString
                    }
                    else
                    {
                      If ($paramsArray -notcontains $paramString)
                      {
                        $paramsArray+=$paramString
                      }
                    }
            }
        }

write-host $paramsArray

The output generated is- enter image description here

Since this is an array you can iterate and use it later in the script.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot