LoginSignup
3
2

More than 5 years have passed since last update.

terraform output variablesで複数の値を返すtips

Posted at

俺です。

terraformのoutput variablesの戻り値はsingle valueです。
aws_instanceリソース内でEC2を複数台起動して、それぞれのパラメータをoutputで返す場合は、
count数分のoutputを記述しないといけません。

間違い

  • ec2.tf
resource "aws_instance" "fueruwakame" {
  ami = "${lookup(var.fueruwakame, "ami")}"
  ..省略..
  private_ip = "172.16.10.${count.index+21}"
  root_block_device {
      volume_type = "${lookup(var.fueruwakame,"root_block_device")}"
      volume_size = "${lookup(var.fueruwakame,"root_block_device_size")}"
  }
  count = "9"
  tags {
    Name  = "fueruwakame${count.index + 1}-${aws_subnet.private-1c-subnet.availability_zone}"
    Role = "db"
    Service = "fueruwakame"
  }
}

output "fueruwakame_private_ips" {
    value = "${aws_instance.fueruwakame.*.private_ip}"
}
orenomac$ terraform plan

Errors:

  * 1 error(s) occurred:

* module root: 1 error(s) occurred:

* output 'fueruwakame_private_ips': multi-variable must be in a slice

汚いけど一つのoutput variableで複数の値を返す方法

あんま綺麗じゃないけどjoin()を使ってしまえばOKです。

  • ec2.tf
resource "aws_instance" "fueruwakame" {
  ami = "${lookup(var.fueruwakame, "ami")}"
  ..省略..
  private_ip = "172.16.10.${count.index+21}"
  root_block_device {
      volume_type = "${lookup(var.fueruwakame,"root_block_device")}"
      volume_size = "${lookup(var.fueruwakame,"root_block_device_size")}"
  }
  count = "9"
  tags {
    Name  = "fueruwakame${count.index + 1}-${aws_subnet.private-1c-subnet.availability_zone}"
    Role = "db"
    Service = "fueruwakame"
  }
}

output "fueruwakame_private_ips" {
  value = "${join(",",aws_instance.fueruwakame.*.private_ip)}"
}
  • apply
orenomac$ terraform apply
Outputs:

  fueruwakame_private_ips   = 172.16.10.21,172.16.10.22,172.16.10.23,172.16.10.24,172.16.10.25,172.16.10.26,172.16.10.27,172.16.10.28,172.16.10.29

多分他にも方法あるはずー。

おわり。

3
2
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
3
2