Search code examples
amazon-web-servicesterraformmapsamazon-vpcsubnet

Would like to identify subnet names to create a map in terraform


I've been trying to find a way to get the subnet names of out of aws... so far no luck. I can find the arn, ids, cidrs... and a bunch of other stuff. But, not names. Help is appreciated!

This is what I'm aiming for. To create a subnet map with the subnet name as the key, and the subnet id as the value. Obviously name IS NOT a supported attribute of data.aws_subnet. I have scoured the 'google' with not luck.

data "aws_subnets" "private" {
  tags = {
    Name = "private*"
  }
  filter {
    name   = "state"
    values = ["available"]
  }
}

data "aws_subnet" "private" {
  for_each = toset(data.aws_subnets.private.ids)
  id       = each.value
}

# wanting to create a map with subnet.name => subnet.id... but, name is an unsupported attribute.
private_subnet_ids = { for s in data.aws_subnet.private : trimprefix(s.name, "private") => s.id }

Solution

  • You have to use tags["Name"]:

    private_subnet_ids = { for s in data.aws_subnet.private : trimprefix(s.tags["Name"], "private") => s.id }