0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

BashでTerraformのoutputからmapの値を取り出して利用する方法

0
Posted at

はじめに

BashでTerraformのoutputからmapの値を取り出して使うことがあったので備忘録的に書いていきます。

方法について

Terraformのoutputの例
output "<output名>" {
  value = {
    for k, v in <リソース>.<リソース名> : k => v.<引数>
  }
}
  • output名
    • terraform outputで取り出すときの名前
  • リソース
    • クラウドのリソースの名前
  • リソース名
    • Terraform内のリソースの名前
  • k
    • mapのキー名
  • v.<引数名>
    • mapの値, 取り出したい引数名
mapのキーを全て取り出したい場合
outputs=( $(terraform output -json <output名> | jq -r 'keys[]') )
mapの値を全て取り出したい場合
outputs=( $(terraform output -json <output名> | jq -r '.[]') )
ループで回したいなら
for output in "${outputs[@]}"; do
    echo "$output"
done

何をしているのか簡単に説明すると、
terraformコマンドでoutputの値をjson形式で出力、
jqコマンドでjson形式の値をbashで利用可能な配列に変換しています。

このスクリプトを実行するにはjqが必要なので、別途インストールしてください。

mac
brew install jq

番外編

特定の値を取り出したい場合
output=$(terraform output -json <output名> | jq -r '.<mapのキー>')

以上です。

最後に

誰かのお役に立てれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?