Rio
Rio

Reputation: 672

terraform create simple loop of variable that can be used later

I am new to terraform development, trying to create simple loop of variable that can be used later, some thing like below:

This perfectly worked for me and creates two subnet as expected.

variable "availability_zones" {
  description = "Available Availability Zones"
  type = "list"
  default = [ "us-east-1a", "us-east-1b" ]
}
variable "public_subnet_cidr" {
  description = "CIDR for Public Subnets"
  type = "list"
  default = [ "10.240.32.0/26", "10.240.32.64/26" ]

# Define Public Subnet
resource "aws_subnet" "public-subnets" {
  count = 2
  vpc_id = "${aws_vpc.default.id}"
  cidr_block = "${element(var.public_subnet_cidr, count.index)}"
  availability_zone = "${element(var.availability_zones, count.index)}"

  tags {
    Name = "${element(var.availability_zones, count.index)}_${element(var.public_subnet_cidr, count.index)}"
  }
}

But while trying to associate those subnets to default route, I am not able to figure out how to fetch individual subnet id from those subnets created earlier. And ended up with below code. Is there a way to fetch subnet.id of individual subnets?

# Assign Default Public Route Table to Public Subnet
resource "aws_route_table_association" "default_public_route" {
  subnet_id = "${aws_subnet.public-subnets.id}"     <<-- This is the line I am trying to figure out
  route_table_id = "${aws_route_table.default_public_route_table.id}"
}

Thanks in advance. Sam

Upvotes: 0

Views: 499

Answers (1)

Tyler Smith
Tyler Smith

Reputation: 528

You're close on how to use it. Here's a walk through that can help you.

resource "aws_route_table_association" "default_public_route" {
  count = 2
  subnet_id = "${element(aws_subnet.public-subnets.*.id, count.index)}"
  route_table_id = "${aws_route_table.default_public_route_table.id}"
}

Upvotes: 1

Related Questions