Search code examples
amazon-web-servicesterraformterraform-provider-aws

How to pass subnet ids to aws_network_interface which has count attribute


I am getting the 3 existing subnet ids using data resource as below

data "aws_subnet" "AZA" {
  vpc_id = var.vpc_id

 filter {
    name   = "tag:Name"
    values = ["my-subnet-1a"]
  }

}

Similarly I'm getting AZB and AZC as well. Now I need to pass these subnet ids to aws_network_interface resource which has count attribute.

resource "aws_network_interface" "my_network_interface" {
    count          = 3
    private_ips     = [var.private_ips[count.index]]
    subnet_id       = ???

How do I pass subnet_id in each iteration?


Solution

  • The better way is to use aws_subnets (not aws_subnet):

    data "aws_subnets" "AZ" {
      filter {
        name   = "tag:Name"
        values = ["my-subnet-1a", "my-subnet-1b", "my-subnet-1c"] 
      }
    }
    

    then

    resource "aws_network_interface" "my_network_interface" {
        count          = 3
        private_ips     = [var.private_ips[count.index]]
        subnet_id       = data.aws_subnets.AZ.ids[count.index]
    }