terraform iterate to associate aws resources

huangapple go评论55阅读模式
英文:

terraform iterate to associate aws resources

问题

我尝试在Terraform上创建NAT网关,对于我创建的每个公共子网。

我创建公共子网如下:

resource "aws_subnet" "public_subnet" {
  count = length(var.vpc.public_subnets)

  vpc_id            = aws_vpc.vpc.id
  availability_zone = var.vpc.public_subnets[count.index].availability_zone
  cidr_block        = var.vpc.public_subnets[count.index].cidr_block
  tags              = var.vpc.public_subnets[count.index].tags
}

我创建所有弹性IP如下:

resource "aws_eip" "eip" {
  for_each = { for eip in var.vpc.eip : eip.name => eip }

  vpc  = true
  tags = each.value.tags
}

最后,我有一个资源块来创建3个NAT网关。每个NAT网关必须使用一个子网和一个EIP:

resource "aws_nat_gateway" "ngw" {
  count = length(var.vpc.public_subnets)

  allocation_id = element(aws_eip.eip.*.allocation_id, count.index)
  subnet_id     = element(aws_subnet.public_subnet.*.id, count.index)
}

结果 ==> 此对象没有名为"allocation_id"的属性。

我应该如何迭代两个资源以为每个子网/EIP对创建NAT网关?

谢谢。

英文:

I try to create nat gateway on terraform, on each public subnets that I created.

I create the public subntes like that:

resource "aws_subnet" "public_subnet" {
  count = length(var.vpc.public_subnets)

  vpc_id            = aws_vpc.vpc.id
  availability_zone = var.vpc.public_subnets[count.index].availability_zone
  cidr_block        = var.vpc.public_subnets[count.index].cidr_block
  tags              = var.vpc.public_subnets[count.index].tags
}

I create all elastic ip like that:

resource "aws_eip" "eip" {
  for_each = { for eip in var.vpc.eip : eip.name => eip }

  vpc  = true
  tags = each.value.tags
}

And finally I have a resource block to create 3 nat gateways. Each nat gateway have to use a subnet and an eip:

resource "aws_nat_gateway" "ngw" {
  count = length(var.vpc.public_subnets)

  allocation_id = element(aws_eip.eip.*.allocation_id, count.index)
  subnet_id     = element(aws_subnet.public_subnet.*.id, count.index)
}

results ==> This object does not have an attribute named "allocation_id"

How should I iterate over 2 resources to create the nat gateay for each pair of subnet/eip ?

thanks.

答案1

得分: 0

由于您在 eip 上使用 for_each,它将是一个 映射(map),而不是一个列表。因此,要访问其值,您可以使用 values

allocation_id = element(values(aws_eip.eip)[*].allocation_id, count.index)
英文:

Since you are using for_each for eip it will be a map, not a list. Thus to access its values you can use values:

allocation_id = element(values(aws_eip.eip)[*].allocation_id, count.index)

huangapple
  • 本文由 发表于 2023年2月10日 05:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定