我正面临shell脚本的问题。我试图读取可用的环境变量(由用户传递),如果存在,我想将它们附加到cmd下面这个cmd—>terraform plan
为了实现这一点,我读取所有已知的输入变量,并准备一个字符串,看起来像这样——>'-var="db_ebs_volume_size=16" -var="db_dns_ttl=9999" '
然后使用cmd——>将变量的内容回显到文件中;echo $temp > temp.txt
然后尝试执行这个整体cmd,它会失败,错误如下:
terraform plan $(cat temp.txt)
错误:-
│ Error: Value for undeclared variable
│
│ A variable named ""db_dns_ttl" was assigned on the command line, but the
│ root module does not declare a variable of that name. To use this value,
│ add a "variable" block to the configuration.
╵
╷
│ Error: Value for undeclared variable
│
│ A variable named ""db_ebs_volume_size" was assigned on the command line,
│ but the root module does not declare a variable of that name. To use this
│ value, add a "variable" block to the configuration.
我不知道为什么内部cmd的输出在双引号之前包含反斜杠(),这会导致这里的问题。如果我尝试运行这个cmd,它工作正常:terraform plan -var="db_ebs_volume_size=16" -var="db_dns_ttl=9999"
我也尝试使用,但仍然看到相同的错误"$(cat temp_cmd.txt |sed 's/\{1}/\\/g' )"
谁能帮助我如何避免这个反斜杠前双引号,使它返回所需的字符串和完整的可以工作。
简短回答:不要在temp.txt
中存储双引号稍长的答案:将变量存储在.tfvars
文件中,并使用-var-file
代替
解释:
引号用于允许shell解析输入:
$ a="1 2 3 4 5"
$ echo "[$a]"
[1 2 3 4 5]
$ b='"1 2 3 4 5"'
$ echo "[$b]"
["1 2 3 4 5"]
在上面的第一个例子中,双引号用来保护空格。
在第二种情况下,外层的单引号保护空格,双引号被认为是值本身的一部分。
当您执行$(cat temp.txt)
时,shell认为cat返回的所有内容都是值的一部分—包括双引号:
$ echo "a" > f
$ cat f
a
$ v=$(cat f)
$ echo "[$v]"
[a]
$ echo '"b"' > f
$ cat f
"b"
$ v=$(cat f)
$ echo "[$v]"
["b"]
当您直接运行命令时:
terraform plan -var="db_ebs_volume_size=16" -var="db_dns_ttl=9999"
, shell将行解析为:
- 程序:
terraform
参数1:
plan
参数2:-var=db_ebs_volume_size=16
参数3:-var=db_dns_ttl=9999
调用terraform
并将三个参数传递给它。
当terraform
程序查看参数2时,它将其解析为:
- 命令
-var
- 第一个
=
告诉它期望一个名称=值对 - 名称:
db_ebs_volume_size
- 第二个
=
表示名称结束/值开始 - value:
16
当你运行:
terraform plan $(cat temp.txt)
shell首先获取cat temp.txt
的值,然后用空格分隔它,生成:
- 程序:
terraform
- 参数1:
plan
- 参数2:
-var="db_ebs_volume_size=16"
- 参数3:
-var="db_dns_ttl=9999"
当terraform
运行时,将参数2解析为:
- 命令:
-var
- 第一个
=
告诉它期望一个名称=值对 - 名称:
"db_ebs_volume_size
- 第二个
=
表示名称结束/值开始 - value:
16"
所以,为了让你的代码正常工作,不要存储双引号——它们是不需要的:
$ cat temp.txt
-var=db_ebs_volume_size=16 -var=db_dns_ttl=9999
更好的是,通过将变量存储在.tfvars
文件中并使用-var-file
加载来完全避免shell解析问题:
$ cat my.tfvars
db_ebs_volume_size = 16
db_dns_ttl = 9999
$ terraform plan -var-file=my.tfvars
你试过用printf代替echo吗?在bash脚本中使用printf有几个优点。我在bash中遇到了来自echo的行结束符的问题。