我有一个variables.tf文件,其中包含所有项目变量,im试图使用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"
}使用PowerShell,我需要能够为我想要的任何变量获取变量值。
示例:如果variables.tf中有多个值,则该命令应该为我提供一个包含所有产品变量的数组。
写主机$product_list
产品-1
产品-2
产品-3
产品-4
如果变量有一个值,那么它应该给出类似于"location“变量的值。
写主机$deployed_location
魏斯特罗普
发布于 2022-06-23 12:01:29
我能够通过下面的方法来解决这个问题,希望这能帮助有类似需求的人。下面的命令将获取variables.tf文件中的任何变量值,在本例中是变量"products",并将其分配给另一个数组变量。
$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发布于 2022-05-01 01:14:11
我遇到了一个类似的问题,所以,我可以分享一种方法,您可以使用它来提取值。问题是,在json或其他格式中很容易提取和操作值,但在tf文件中则不一样。因此,我基本上已经使用了一种解决办法,在一个结构中设置给定的文件,而这个结构的值是用一行填充的,因此,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"
}接下来是PS代码来提取变量的值-
$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所产生的输出是-

因为这是一个数组,所以您可以在脚本中迭代并使用它。
https://stackoverflow.com/questions/72055453
复制相似问题