Home > database >  How to pass subnet ids to aws_network_interface which has count attribute
How to pass subnet ids to aws_network_interface which has count attribute

Time:07-11

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?

CodePudding user response:

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

CodePudding user response:

Had a similar situation. I have used locals to concat the subnet ids

locals {
  subnets = concat([data.aws_subnet.AZA.id],[data.aws_subnet.AZB.id],[data.aws_subnet.AZC.id])
}

resource "aws_network_interface" "my_network_interface" {
    count          = 3
    private_ips    = [var.private_ips[count.index]]
    subnet_id      = local.subnets[count.index]
  • Related