Skip to content

Instantly share code, notes, and snippets.

@mamemomonga
Last active August 18, 2020 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamemomonga/ad36a9f98f2d2d3935e36cf090fca5c8 to your computer and use it in GitHub Desktop.
Save mamemomonga/ad36a9f98f2d2d3935e36cf090fca5c8 to your computer and use it in GitHub Desktop.
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