1

我遇到了以下问题(terraform v0.12.8);

我试图在下面用作我的模块代码并将它们传递给下面的资源;

module "nat_gateway" {
    source           = "../providers/aws/network/nat_gw/"
    total_nat_gws    = "${length(var.availability_zones)}"
    eip_id           = "${module.eip.*.eip_id}"
    target_subnet_id = "${module.public_subnet.*.subnet_id}"
    nat_gw_name_tag  = "NAT-${var.stack_name}"
}
resource "aws_nat_gateway" "nat_gw" {
    count         = "${var.total_nat_gws}"
    allocation_id = "${element("${var.eip_id}", count.index)}"
    subnet_id     = "${element("${var.target_subnet_id}", count.index)}"

    tags = {
        Name = "${var.nat_gw_name_tag}"
    }
}

我预计,它将使用提供的多个 EIP 和子网创建多个 NAT 网关。但因以下错误而失败;

Error: Incorrect attribute value type

  on ../providers/aws/network/nat_gw/nat_gateway.tf line 12, in resource "aws_nat_gateway" "nat_gw":
  12:     allocation_id = "${element("${var.eip_id}", count.index)}"

Inappropriate value for attribute "allocation_id": string required.


Error: Incorrect attribute value type

  on ../providers/aws/network/nat_gw/nat_gateway.tf line 12, in resource "aws_nat_gateway" "nat_gw":
  12:     allocation_id = "${element("${var.eip_id}", count.index)}"

Inappropriate value for attribute "allocation_id": string required.


Error: Incorrect attribute value type

  on ../providers/aws/network/nat_gw/nat_gateway.tf line 13, in resource "aws_nat_gateway" "nat_gw":
  13:     subnet_id     = "${element("${var.target_subnet_id}", count.index)}"

Inappropriate value for attribute "subnet_id": string required.


Error: Incorrect attribute value type

  on ../providers/aws/network/nat_gw/nat_gateway.tf line 13, in resource "aws_nat_gateway" "nat_gw":
  13:     subnet_id     = "${element("${var.target_subnet_id}", count.index)}"

有人可以帮助纠正我。

4

1 回答 1

1

你用嵌套的大括号错误地插入了东西。

相反,这应该如下所示:

resource "aws_nat_gateway" "nat_gw" {
  count         = "${var.total_nat_gws}"
  allocation_id = "${element(var.eip_id, count.index)}"
  subnet_id     = "${element(var.target_subnet_id, count.index)}"

  tags = {
    Name = "${var.nat_gw_name_tag}"
  }
}

由于您不依赖于element允许通过选择比长度更长的索引来循环返回列表的行为,因此您可以将其简化为:

resource "aws_nat_gateway" "nat_gw" {
  count         = "${var.total_nat_gws}"
  allocation_id = "${var.eip_id[count.index]}"
  subnet_id     = "${var.target_subnet_id[count.index]}"

  tags = {
    Name = "${var.nat_gw_name_tag}"
  }
}

因为您使用的是 Terraform 0.12,所以您也可以直接使用变量而不是使用插值语法来更进一步:

resource "aws_nat_gateway" "nat_gw" {
  count         = var.total_nat_gws
  allocation_id = var.eip_id[count.index]
  subnet_id     = var.target_subnet_id[count.index]

  tags = {
    Name = var.nat_gw_name_tag
  }
}
于 2019-09-16T13:22:10.997 回答