我可以将 terraform 输出设置为 env 变量吗?

Ser*_* Vu 6 bash terminal terraform hashicorp-vault

所以 terraform 生成了一堆我感兴趣的输出。如何将这些值通过管道传输到环境变量或其他东西,以便我的脚本能够在有人运行后获取它们terraform apply

con*_*fiq 17

如前所述,您不能从 中获取值terraform apply,您可以使用terraform output.

我还建议使用-raw, 来自帮助

  -raw             For value types that can be automatically
                   converted to a string, will print the raw
                   string directly, rather than a human-oriented
                   representation of the value.
Run Code Online (Sandbox Code Playgroud)

我如何使用的示例:

KMS_KEY_ID=$(terraform output -raw kms_secrets_id)

我希望它能帮助别人


Mar*_*ins 9

Terraform 不能直接修改调用它的 shell 的环境——通常,一个程序在启动子程序本身时只能修改它自己的环境或设置一个新的环境——所以这里的任何解决方案都将涉及在调用一次 shell terraform apply返回就。

一种方法是将输出通过管道传输terraform output -json到一个程序中,该程序可以解析 JSON,提取相关值,然后将它们作为一个或多个 shell 语句打印出来以设置环境变量。然后,您可以将该程序的结果作为 shell 脚本运行,例如使用sourcebash 中的命令,将这些环境变量值合并到您当前的 shell 中。

您可以使用您熟悉的任何编程语言编写此转换程序。对于简单的情况,您可能想使用 编写一个简单的 shell 脚本jq,依靠其@sh转义模式来保证值的有效 shell 引用:

terraform output -json | jq -r '@sh "export EXAMPLE1=\(.example1.value)\nexport EXAMPLE2=\(.example2.value)"'
Run Code Online (Sandbox Code Playgroud)

我使用以下测试 Terraform 配置尝试了此操作:

output "example1" {
  value = "hello"
}

output "example2" {
  value = <<EOT
Hello world
This is a multi-line string with 'quotes' in "it".
EOT
}
Run Code Online (Sandbox Code Playgroud)

应用该配置后,上面的命令产生以下输出:

export EXAMPLE1='hello'
export EXAMPLE2='Hello world
This is a multi-line string with '\''quotes'\'' in "it".
'
Run Code Online (Sandbox Code Playgroud)

我将输出重定向到一个文件env.sh,然后将其加载到我的 shell 中以确认变量可用:

$ terraform output -json | jq -r '@sh "export EXAMPLE1=\(.example1.value)\nexport EXAMPLE2=\(.example2.value)"' >env.sh
$ source env.sh 
$ echo $EXAMPLE1
hello
$ echo "$EXAMPLE2"
Hello world
This is a multi-line string with 'quotes' in "it".

Run Code Online (Sandbox Code Playgroud)

(请注意,因为EXAMPLE2我将变量插值放在引号中,否则 shell 会将每个空格分隔的单词理解为一个单独的参数,而不是将整个值视为一个包含所有空白字符的单个字符串。)