dzbeda
dzbeda

Reputation: 303

Terraform - How to loop on Specific subnets

I'm running terraform that creates 4 Subnets , 2 of the subnets are public and the name starts with "public".

Subnet code

Private subnet

resource "aws_subnet" "private-subnet-az-a" {
  availability_zone = "us-east-1a"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.1.0/24"
  map_public_ip_on_launch = false
}
resource "aws_subnet" "private-subnet-az-b" {
  availability_zone = "us-east-1b"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.2.0/24"
  map_public_ip_on_launch = false
}
## Public subnet
resource "aws_subnet" "public-subnet-az-a" {
  availability_zone = "us-east-1a"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.3.0/24"
  map_public_ip_on_launch = true
}
resource "aws_subnet" "public-subnet-az-b" {
  availability_zone = "us-east-1b"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.4.0/24"
  map_public_ip_on_launch = true
}

When creating Load Balancer I need to attach it both public sunsets - i have tries the For as you can see in the example, but it is not working

## Create lb code ; [for subnet in aws_subnet.public-[*].id : subnet]

resource "aws_lb" "nlb" {
    name               = "nlb-web"
    internal           = false
    load_balancer_type = "network"
    subnets            = [for subnet in aws_subnet.public-[*].id : subnet]
}

Upvotes: 1

Views: 2728

Answers (1)

Marcin
Marcin

Reputation: 238061

You can't construct such a loop. The proper way of doing this is to create a map and use for_each to create your subnets:

variable "subnets"  {
  default = {
      private-subnet-az-a = {
          cidr_block = "10.0.1.0/24"
          map_public_ip_on_launch = false
          availability_zone = "us-east-1a"
      }
      private-subnet-az-a = {
          cidr_block = "10.0.1.0/24"
          map_public_ip_on_launch = false
          availability_zone = "us-east-1b"
      }
      # and so on      
  }
}

resource "aws_subnet" "subnet" {

  for_each = var.subnets

  availability_zone = each.value.availability_zone
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = each.value.cidr_block
  map_public_ip_on_launch = each.value.map_public_ip_on_launch
}


resource "aws_lb" "nlb" {
    name               = "nlb-web"
    internal           = false
    load_balancer_type = "network"
    subnets            = [for key, subnet in aws_subnet.subnet : subnet.id if length(regexall("public.*", key)) > 0]
}

Upvotes: 2

Related Questions