地形化多个for_each资源

时间:2019-11-14 16:32:16

标签: terraform

我已经使用for_each循环创建了多个子网和多个VPC端点,如下所示:

### VARIABLES ###

variable "private_cidr_mask" {
  default = {
    "us-west-1a" = "10.0.1.0/24"
    "us-west-1b" = "10.0.2.0/24"
  }
}

variable "vpc_endpoints" {
  default = [
    "com.amazonaws.us-west-1.ecs-agent",
    "com.amazonaws.us-west-1.ecs-telemetry",
    "com.amazonaws.us-west-1.ecs"
  ]
}

### RESOURCES ###

resource "aws_subnet" "private_subnet" {

  for_each = var.private_cidr_mask

  vpc_id = aws_vpc.vpc.id
  availability_zone = each.key
  cidr_block = each.value
}

resource "aws_vpc_endpoint" "vpc_endpoint" {

  for_each = toset(var.vpc_endpoints)

  vpc_id = aws_vpc.vpc.id
  vpc_endpoint_type = "Interface"
  service_name = each.value

  security_group_ids = [ aws_security_group.security_group.id ]

  private_dns_enabled = true
}

现在,我必须使用aws_vpc_endpoint_subnet_association将每个VPC端点分配给每个专用子网:

resource "aws_vpc_endpoint_subnet_association" "vpc_endpoint_subnet_association" {
  vpc_endpoint_id = <every endpoint>
  subnet_id = <every subnet>
}

如何在Terraform中实现这一目标?我尝试了嵌套的for_each循环,但没有成功。

2 个答案:

答案 0 :(得分:0)

在aws_vpc_endpoint_subnet_association资源创建之内

您是否考虑过根据查找vpc_endpoints的数量使用count命令?

然后您可以为其中的每个子网ID设置一个。

答案 1 :(得分:0)

事实证明,aws_vpc_endpoint接受了subnet_ids的列表,而我只是在文档中错过了它,所以我要做的就是:

resource "aws_vpc_endpoint" "vpc_endpoint" {

  for_each = toset(var.vpc_endpoints)

  vpc_id = aws_vpc.vpc.id
  vpc_endpoint_type = "Interface"
  service_name = each.value

  security_group_ids = [ aws_security_group.security_group.id ]
  subnet_ids = [ for subnet in aws_subnet.private_subnet: subnet.id ]

  private_dns_enabled = true
}