Home > database >  Create aws_subnet using for_each loop in Terraform
Create aws_subnet using for_each loop in Terraform

Time:05-05

I create resource "aws_subnet" using count expression. I'd like to use for_each instead of count, but need help with the correct syntax.

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"
  }
}

CodePudding user response:

One way to use for_each would be as follows:

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"
  }
}

The simpler way would be:

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"
  }
}
  • Related