31
19

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 5 years have passed since last update.

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

Posted at

やること

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")}"]}
31
19
2

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
31
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?