Help us understand the problem. What is going on with this article?

Terraformのoutputでmapを利用する方法

More than 3 years have passed since last update.

やること

Terraformのoutputでmapを利用する

なにが嬉しいか

module間で値を受け渡す時のoutputの定義が短くなる

Befor: 冗長的なoutput

output側の定義
output "vpc_id" {
  value = "${aws_vpc.vpc.id}"
}

output "public-a" {
  value = "${aws_subnet.public-a.id}"
}

output "public-c" {
  value = "${aws_subnet.public-c.id}"
}

output "private-a" {
  value = "${aws_subnet.private-a.id}"
}

output "private-c" {
  value = "${aws_subnet.private-c.id}"
}
moduleから呼び出す時
module "compute" {
  source = "../../xxx"

  vpc_id     = "${module.xxx.vpc_id}"
  public-a   = "${module.xxx.public-a}"
  public-c   = "${module.xxx.public-c}"
  private-a  = "${module.xxx.private-a}"
  private-c  = "${module.xxx.private-c}"
}

After: mapを使ったoutput

outputの際にvalueの値に "${map("key", "value")}" を入れることでmapとして利用可能になる。

output側の定義
output "vpc" {
  value = "${
    map(
      "vpc_id",           "${aws_vpc.vpc.id}",
      "subnet-public-a",  "${aws_subnet.public-a.id}",
      "subnet-public-c",  "${aws_subnet.public-c.id}",
      "subnet-private-a", "${aws_subnet.private-a.id}",
      "subnet-private-c", "${aws_subnet.private-c.id}"
    )
  }"
}
moduleから呼び出す時
module "compute" {
  source = "../../xxx"
  vpc = "${module.xxx.vpc}"
}

スッキリ!!

参照方法

ちなみに以下のようにlookupでkeyを指定することでvalueを参照出来る。

.tf
subnet_ids = ["${lookup(var.vpc, "subnet-private-a")}"]}
shogomuranushi
AWSが得意系(資格5冠ホルダー)のインフラエンジニア
https://medium.com/@shogomuranushi
abeja
「ディープラーニング」を活用し、多様な業界、シーンにおけるビジネスの効率化・自動化を促進するベンチャー企業です。
https://abejainc.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away