AWS
Terraform

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

More than 1 year has 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")}"]}