user630702
user630702

Reputation: 3127

Local variables in parameters values

Is it normal that local variables can't be used in place of route_table_id or in resource names? It seems to be working only with tags and where name = are used or am I not doing it correctly?

locals {
  public_subnet_name = "public_test"
  private_subnet_name = "private_test"
}

# Create Subnet
resource "aws_subnet" "public_test_a" {
  vpc_id = aws_vpc.vpc_test_02.id
  cidr_block = "10.0.0.0/28"
  map_public_ip_on_launch = true
  availability_zone = var.AZ[0]

  tags = {
    Name = "${local.public_subnet_name}_a"      # It works here
  }
}

But doesn't work in route_able_id or in resource names.

# Associate route table to subnets
resource "aws_route_table_association" "public_test_1" {        # can't replace public_test with local
  subnet_id = aws_subnet.public_test_a.id
  route_table_id = aws_route_table.public_test.id               # can't replace public_test with local
}

resource "aws_route_table_association" "public_test_2" {        # can't replace public_test with local
  subnet_id = aws_subnet.public_test_b.id
  route_table_id = aws_route_table.public_test.id               # can't replace public_test with local
}

Upvotes: 0

Views: 83

Answers (1)

Marcin
Marcin

Reputation: 238209

Yes. That's why you should use for_each or count in cases like yours.

For example, you could define your public subnets as follows:

variable "public_cidr" {
  default = {
      public_test_1 = "10.0.0.0/24"
      public_test_2 = "10.0.2.0/24"
      public_test_3 = "10.0.4.0/24"
      }
}

resource "aws_subnet" "public" {

  for_each          = var.public_cidr
  
  vpc_id            = aws_vpc.main.id
  cidr_block        = each.value
  availability_zone = data.aws_availability_zones.available.names[0]
  
  map_public_ip_on_launch = true
  
  depends_on = [aws_internet_gateway.igw]
  
  tags = {
    Name = "public-${each.key}"
  }    
}

This way you could refer to the individual subnets as:

aws_subnet.public["public_test_1"]
aws_subnet.public["public_test_2"]
aws_subnet.public["public_test_3"]

Subsequently, your route table association could be:

resource "aws_route_table_association" "association" { 

  for_each  = aws_subnet.public

  subnet_id = each.value.id
  route_table_id = aws_route_table.rt.id      
}

Upvotes: 1

Related Questions