Search code examples
amazon-web-servicesterraformterraform-provider-awsamazon-vpc

Sorting subnets by name in Terraform v0.11.14


I'm trying to grab a list of subnets by name, filter out the ones which end in "d" (for the "d" Availability Zone), and then grab the IDs of the remaining subnets in Terraform v0.11.14. This is how I create the subnets:

resource "aws_subnet" "private" {
  vpc_id            = "${var.vpc_id}"
  cidr_block        = "${element(split(",", var.cidrs), count.index)}"
  availability_zone = "${element(split(",", var.azs), count.index)}"
  count             = "${length(split(",", var.cidrs))}"

  tags      { Name = "${var.name}.${element(split(",", var.azs), count.index)}" }
  lifecycle { create_before_destroy = true }
}

I know how to achieve my result in Terraform v1.0.0:

output "subnet_ids" { value = "${join(",", list(for subnet in aws_subnet.private.*: subnet.id if substr(subnet.name, -1, 1) != "d" ))}" }

I'm trying to do the same thing in Terraform v0.11.14 by just cutting off the last subnet in hopes that the subnets are by default sorted by name, but they aren't:

output "subnet_ids" { value = "${join(",", slice(aws_subnet.private.*.id, 0, length(aws_subnet.private.*.id) - 1))}" }

Anyone know how to achieve what I'm trying to do with Terraform v0.11.14?


Solution

  • You can check the following. As I understand, your filtering is based on the last letter of AZ name. Thus maybe you can sort by AZ, and remove last one, as you tried:

    locals {
        sorted_az  = "${sort(aws_subnet.private.*.availability_zone)}"
        length_az_minus_1  = "${length(local.sorted_az)-1}"
        azs_without_last = "${slice(local.sorted_az, 0, local.length_az_minus_1)}"   
    }
    
    output "subnet_ids" { 
      value = "${ matchkeys(aws_subnet.private.*.id, aws_subnet.private.*.availability_zone, local.azs_without_last)}"
    }