在 Terraform 中使用 for_each 循环创建 aws_subnet

Create aws_subnet using for_each loop in Terraform

我使用计数表达式创建资源“aws_subnet”。我想使用 for_each 而不是计数,但需要有关正确语法的帮助。

variable "privateSubnetCIDR" {
      type = list(string)
      default = ["10.0.1.0/24","10.0.2.0/24"]
    }
data "aws_availability_zones" "availableAZ" {}
    
resource "aws_subnet" "privatesubnet" {
  count                   = length(var.privateSubnetCIDR)
  cidr_block              = tolist(var.privateSubnetCIDR)[count.index]
  vpc_id                  = aws_vpc.dev_vpc.id
  map_public_ip_on_launch = false
  availability_zone       = data.aws_availability_zones.availableAZ.names[count.index]
  tags = {
    name        = "${var.environment}-privatesubnet-${count.index + 1}"
    AZ          = data.aws_availability_zones.availableAZ.names[count.index]
    Environment = "${var.environment}-privatesubnet"
  }
}

使用 for_each 的一种方法如下:

resource "aws_subnet" "privatesubnet" {
  for_each                = toset(var.privateSubnetCIDR)
  cidr_block              = each.key
  vpc_id                  = aws_vpc.dev_vpc.id
  map_public_ip_on_launch = false
  availability_zone       = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
  tags = {
    name        = "environment-privatesubnet-${index(var.privateSubnetCIDR, each.key) + 1}"
    AZ          = element(data.aws_availability_zones.availableAZ.names, index(var.privateSubnetCIDR, each.key))
    Environment = "environment-privatesubnet"
  }
}

更简单的方法是:

resource "aws_subnet" "privatesubnet" {
  for_each                = {for idx, val in var.privateSubnetCIDR: idx => val}
  cidr_block              = each.value
  vpc_id                  = aws_vpc.dev_vpc.id
  map_public_ip_on_launch = false
  availability_zone       = element(data.aws_availability_zones.availableAZ.names, each.key)
  tags = {
    name        = "environment-privatesubnet-${each.key + 1}"
    AZ          = element(data.aws_availability_zones.availableAZ.names, each.key)
    Environment = "environment-privatesubnet"
  }
}