Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
terraform の出力をbash変数として利用する方法

terraform の出力をbash変数として利用する方法

jq, perlを使用する

main.tf の作成

$ cat > main.tf << 'EOS'
output env {
  value = {
    VALUE1 = "the value1"
    VALUE2 = "the value2"
    VALUE3 = "the value3"
    VALUE4 = "the value4"
  }
}
EOS

terraform 初期化

$ terrafrom init

terraform 適用

$ terraform apply

Outputs:

env = {
  "VALUE1" = "the value1"
  "VALUE2" = "the value2"
  "VALUE3" = "the value3"
  "VALUE4" = "the value4"

出力をbash環境変数に変換

$ terraform output -json env | \
  jq -r '. | to_entries | map(.key+"="+(.value|tostring)) | .[]' | \
  perl -nlpE 's!^([^=]+)=(.+)!$1="$2"!' > env

内容の確認

$ cat env

VALUE1="the value1"
VALUE2="the value2"
VALUE3="the value3"
VALUE4="the value4"

bashからの使用例

$ bash << 'EOS'
source ./env
echo $VALUE3
EOS

the value3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment