Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract Subnet ID from List Terraform

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading