3

I have a list of subnets IDs and I want to get an array of the cidr_blocks associated to each subnet.

variable "aws_subnet_ids" {
  type = list(string)
  default = ["subnet-aaaaaaaa","subnet-bbbbbbbb"]
}

desired_output = ['10.0.1.0/24', '10.0.2.0/24']

I've been fiddling around with for loops and count data for a quite a while for what should be a really simple problem. But I'm having a hard time finding an appropriate way to actually do this.

This seemed like a decent example to work off of, but you can't actually use a for_each in a data source off a list of strings. https://www.terraform.io/docs/providers/aws/d/subnet_ids.html

data "aws_subnet" "example" {
  for_each = var.aws_subnet_ids
  cidr_blocks       = each.cidr_block
}

output "subnet_cidr_blocks" {
  value = [for s in data.aws_subnet.example : s.cidr_block]
}

1 Answer 1

3
data "aws_subnet" "subnets" {
  for_each = toset(var.aws_subnet_ids)
  id       = each.value
}

locals {
  cidr_blocks = [
    for subnet in data.aws_subnet.subnets :
      subnet.cidr_block
    ]

  cidr_blocks_rendered = [
    for cidr_block in local.cidr_blocks :
     {
       from_port   = 6443,
       to_port     = 6443,
       protocol    = "tcp",
       cidr_blocks = cidr_block
     }
  ]
}

output "output1-1" {
  value = local.cidr_blocks_rendered
}

This is what ultimately I needed.

2
  • Exactly what I was looking for, thank you.
    – sbaxter
    Commented Sep 1, 2020 at 2:04
  • Shortcut: data.aws_subnet.subnets[*].cidr_block
    – Anton
    Commented May 6, 2021 at 2:21

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.