使用bash脚本编辑.tf变量文件



tf文件中有一个很大的变量文件,我想使用bash脚本更改值。

像我的文件有很多这样的块,我想一步一步地改变每个块。改变地形文件变量值的最佳实践是什么?

variable "azure_spoke_gateways" {
default = {
spoke1 = {
name         = "name"
size         = "size"
vpc          = ""
},
spoke2 = {
name         = "dummy"
size         = "size2"
}
}
}

如果您拥有该文件,并且可以从头开始生成它,而不是编辑现有文件,则可以使用以下方法。

cat << EOF > main.tf.sh
variable "azure_spoke_gateways" {
default = {
spoke1 = {
name    = "AZ-${region}-Spoke1-GW"
size       = "Standard_B1ms"
.. 
}
}
}
EOF
chmod +x main.tf.sh
export region=EU
. ./main.tf.sh > main.tf

虽然它仅限于特定的场景,但非常简单明了。

使用GNU awk:

在进行之前设置变量

spke="spoke1" # The spoke we are concerned with
var="size" # The variable within the spoke section we are concerned with
val="size1" # The value we want to change to.
clp="azure" # Either azure or aws

使用-v 将这些变量传递到GNU awk

awk -v spke="$spke" -v var="$var" -v val="$val" -v clp="$clp"'
/variable/ { 
cloudp=gensub(/(^variable[[:space:]]")(.*)(".*$)/,"\2",$0) # Pull out the cloud provider
}
/spoke[[:digit:]][[:space:]]=/ { 
spoke=$1 # Track the spoke section
} 
spoke==spke && $1==var && cloudp ~ clp { # If spoke is equal to the passed spoke and the first space separated field is equal to the variable and clp is equal to the passed cloud provider (clp) we want to change (var)
$0=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",$0) # Substitute the value for the value passed (val)
}1' file

单行

awk -v spke="$spke" -v var="$var" -v val="$val" -v clp="$clp" '/variable/ { cloudp=gensub(/(^variable[[:space:]]")(.*)(".*$)/,"\2",$0) } /spoke[[:digit:]][[:space:]]=/ { spoke=$1 } spoke==spke && $1==var && cloudp ~ clp { $0=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",$0) }1' file

如果您有GNU awk的最新版本,您可以通过简单地添加-i标志来提交对文件的更改,因此:

awk -i -v spke="$spke" -v var="$var" -v val="$val" -v clp="$clp" '/variable/ { cloudp=gensub(/(^variable[[:space:]]")(.*)(".*$)/,"\2",$0) } /spoke[[:digit:]][[:space:]]=/ { spoke=$1 } spoke==spke && $1==var && cloudp ~ clp { $0=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",$0) }1' file

否则:

awk -v spke="$spke" -v var="$var" -v val="$val" -v clp="$clp" '/variable/ { cloudp=gensub(/(^variable[[:space:]]")(.*)(".*$)/,"\2",$0) } /spoke[[:digit:]][[:space:]]=/ { spoke=$1 } spoke==spke && $1==var && cloudp ~ clp { $0=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",$0) }1' file > file.tmp && mv -f file.tmp file 

如果您以Terraform JSON格式存储变量,我建议您使用支持JSON的东西,如JQ,而不是使用sed/awk等天真地修改JSON。这样,您应该能够可靠地维护JSON格式。

如果你需要维护原始格式,我理解为HCL,也许可以使用HCL解析器编写一个脚本,比如这个

最新更新