0

I have a list of CIDRs for my subnets and want to get their ids. Is it possible to do with terraform?

my_subnets = ["212.12.1.0/24", "212.12.2.0/24", "212.12.3.0/24"]

I know VPC id as well, how to get an array of subnets ids via data source?

The idea is to pass that next as an argument to another module

vpc_options {
    # invalid code, just for illustration
    subnet_ids = data.aws_subnet.my_subnets[*].id
  }

1 Answer 1

1

It seems that you already know which CIDR ranges you wish to look up, and that you are trying to find the corresponding subnet id for each of them.

You can achieve that by using the aws_subnet data source with for_each, to tell Terraform to make a separate call to that data source for each of your CIDR ranges. I'm assuming that the my_subnets example in your question is inside a locals block and so it has declared and defined local.my_subnets to hold that list of strings.

data "aws_subnet" "example" {
  for_each = toset(local.my_subnets)

  cidr_block = each.key
}

A resource with for_each set appears in expressions as a map of objects where the map keys are the same as the for_each map keys (or, in this case, set elements). Therefore you can derive from this a mapping from CIDR block to subnet ID:

locals {
  subnet_ids = tomap({
    for cidr, subnet in data.aws_subnet.example : cidr => subnet.id
  })
}

or, if you don't actually care about the correspondence between the CIDR blocks and the ids and just want a flat set of ids, you can just ignore the instance keys:

locals {
  subnet_ids = toset([
    for subnet in data.aws_subnet.example : subnet.id
  ])
}

The second of these seems to be what is expected by the subnet_ids argument you want to assign to:

  vpc_options {
    subnet_ids = [
      for subnet in data.aws_subnet.example : subnet.id
    ]
  }

(I omitted the toset call when inlining this expression in the argument, because the schema for that vpc_options block will already tell Terraform whether subnet_ids is a set or a list, and so Terraform can convert automatically in that case.)

1
  • thanks, that's exactly what I was looking for Commented Feb 1, 2022 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.