Home > other >  Extract Subnet ID from List Terraform
Extract Subnet ID from List Terraform

Time:10-21

I have a number of Terraform data sources and a locals block created as such

data "aws_subnets" "subs" {
  for_each = toset(["a", "b", "c"])

  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.vpc.id]
  }

  filter {
    name   = "availability-zone"
    values = ["${data.aws_region.region.name}${each.key}"]
  }
}

data "aws_vpc" "vpc" {
  default = false
}

data "aws_region" "region" {}

locals {
   ids = [for az in data.aws_subnets.subs : az.ids[1]]
}

And an output block

output "main" {
    value = local.ids
}

But when I run a terraform apply I get the error

The given key does not identify an element in this collection value: the given index is greater than or equal to the length of the collection

When I take out the index value [1] from my locals block, I can see the output as

    main = [
        [
            "subnet-1234567f3f5d95987",
            "subnet-123456797f61f831e",
            "subnet-123456791ec481316",
        ],
        [
            "subnet-12345674da33e8064",
            "subnet-12345676030bc7040",
        ],
        [],
    ]

How can I extract a particular subnet ID from this list?

CodePudding user response:

You have to consider two things here:

  1. You are using for_each for the data source, so that means the return result will have key value pairs
  2. The return result for each key will be a list

In order to achieve what you want, you need to change to the following code:

data "aws_subnets" "subs" {
  for_each = toset(["a", "b", "c"])

  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.vpc.id]
  }

  filter {
    name   = "availability-zone"
    values = ["${data.aws_region.region.name}${each.key}"]
  }
}

data "aws_vpc" "vpc" {
  default = false
}

data "aws_region" "region" {}

locals {
   ids = values(data.aws_subnets.subs)[*].ids
}

Here, the built-in values [1] function is used to get all the values for all the keys. The return result is also a list, so this will be a list of lists.


[1] https://developer.hashicorp.com/terraform/language/functions/values

  • Related