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

edit .tf variable files using bash script

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

就像我的文件有很多这样的块,我想逐步更改每个块。更改 terraform 文件变量值的最佳做法是什么?

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

如果您将变量存储在 Terraform JSON format, I'd recommend using something JSON-aware, such as JQ 中,而不是使用 sed/awk 等天真地修改 JSON。这样您应该能够可靠地保持你的 JSON 格式。

如果你需要保持原来的格式,我理解的是HCL,也许可以使用HCL解析器写一个脚本,比如this one

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

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",[=11=]) # Pull out the cloud provider
                 }
      /spoke[[:digit:]][[:space:]]=/ { 
                                        spoke= # Track the spoke section
                                     } 
          spoke==spke && ==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)
                                        [=11=]=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",[=11=]) # 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",[=12=]) } /spoke[[:digit:]][[:space:]]=/ { spoke= } spoke==spke && ==var && cloudp ~ clp { [=12=]=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",[=12=]) }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",[=13=]) } /spoke[[:digit:]][[:space:]]=/ { spoke= } spoke==spke && ==var && cloudp ~ clp { [=13=]=gensub(/(^.*=[[:space:]]")(.*)(".*$)/,"\1"val"\3",[=13=]) }1' file

否则:

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