如何使用计数遍历资源中的子网

How to loop through subnets in a resource using count

在 Terraform 0.11.14 中,以下内容可以循环遍历先前在数据变量中检索到的不同子网(参见 https://www.terraform.io/docs/providers/aws/d/subnet_ids.html ):

data "aws_subnet_ids" "private" {
  vpc_id = "${var.vpc_id}"

  tags = {
    Tier = "Private"
  }
}

resource "aws_instance" "app" {
  count         = "3"
  ami           = "${var.ami}"
  instance_type = "t2.micro"
  subnet_id     = "${element(data.aws_subnet_ids.private.ids, count.index)}"
}

但是,由于我迁移到 Terreform 0.12,此语法导致以下错误:

Error: Error in function call

  on ..\..\modules\elk\es-proxy-server.tf line 21, in resource "aws_spot_instance_request" "kibana_proxy":
  21:   subnet_id = "${element(data.aws_subnet_ids.private.ids, count.index)}"
    |----------------
    | count.index is 0
    | data.aws_subnet_ids.private.ids is set of string with 2 elements

Call to function "element" failed: cannot read elements from set of string.

我尝试使用 tolist 函数并弄清楚如何利用以下功能 https://www.terraform.io/upgrade-guides/0-12.html#working-with-count-on-resources 但没有成功。

你应该可以做到:

subnet_id     = "${tolist(data.aws_subnet_ids.private.ids)[count.index]}"