かまたま日記3

プログラミングメイン、たまに日常

Terraformのcountでvariable以外のinterpolationを使えない

version

Terraform 0.6.16

本文

ドキュメント にも書いてあったのですが、Terraformで複数リソースを一気に定義するときに count という項目を使うのですが、ここでは直接数字を入力するか、 variables で定義した値に対するinterpolationしか使えないようです。

例えばこんな感じで、AWSのsubnetごとに1つEC2インスタンスを作るようなtfファイルを書いた場合

resource "aws_subnet" "foo" {
  count = 2
  cidr_block = "${format("10.1.%d.0/24", count.index)}"
  vpc_id = "aaa"
}

resource "aws_instance" "var" {
  count = "${length(aws_subnet.foo.*.id)}"
  ami = "bbb"
  instance_type = "ccc"
  subnet_id = "${element(aws_subnet.foo.*.id, count.index)}"
}

terraform plan を実行するとエラーになります。

Error configuring: 1 error(s) occurred:

* strconv.ParseInt: parsing "${length(aws_subnet.foo.*.id)}": invalid syntax

上記の場合は単純に2をaws_instanceの方のcountに入れてあげれ良いのですが、ちと難しいのが別の tfstate から値を取ってくるような場合。

resource "terraform_remote_state" "foo" {
  backend = "s3"
  config {
    bucket = "kamatama41-tfstate"
    key = "example.tfstate"
  }
}

resource "aws_instance" "var" {
  count = "${length(split(",", terraform_remote_state.foo.output.subnet_ids))}"
  ami = "bbb"
  instance_type = "ccc"
  subnet_id = "${element(split(",", terraform_remote_state.foo.output.subnet_ids), count.index)}"
}

この場合countを計算することが出来ないし、以下のように単なる数字の2をoutputとして定義してもダメなので、現状完全にお手上げ状態です。。

resource "terraform_remote_state" "foo" {
  backend = "s3"
  config {
    bucket = "kamatama41-tfstate"
    key = "example.tfstate"
  }
}

resource "aws_instance" "var" {
  count = "${terraform_remote_state.foo.output.subnet_cidrs_count}"
  ami = "bbb"
  instance_type = "ccc"
  subnet_id = "${element(split(",", terraform_remote_state.foo.output.subnet_cidrs_count), count.index)}"
}

誰か解決策があったら教えて下さい!

Terraformの関連issue

github.com