Jim M.
Jim M.

Reputation: 1009

Terraform getting private subnets for a security group

I am trying to get the private subnets in my VPC, I'm using an example from the Terraform docs https://www.terraform.io/docs/providers/aws/d/subnet_ids.html but this is giving me errors.

Here is my code (I commented out the filter, so this should get all subnets - my vpc has 3 public and 3 private subnets)

data "aws_subnet_ids" "example" {
  vpc_id = var.vpc_id
//  filter {
//    name = "tag:Tier"
//    values = ["private"]
//  }
}

data "aws_subnet" "example" {
  count = length(data.aws_subnet_ids.example.ids)

  id = data.aws_subnet_ids.example.ids[count.index]
}

I get an error on the id = data.aws_subnet_ids... line

I get the following error 6 times, 1 for each index

Error: Invalid index

  on modules/global/data.tf line 20, in data "aws_subnet" "example":
  12:   id = data.aws_subnet_ids.example.ids[count.index]
    |----------------
    | count.index is 5
    | data.aws_subnet_ids.example.ids is set of string with 6 elements

This value does not have any indices.

I'm using HCL2, but just in case I reverted back to previous interpolation ("${data.aws_subnet_ids.example.ids[count.index]}") for all statements with the same results.

help?

Thank you

$ terraform --version
Terraform v0.12.7
+ provider.aws v2.25.0
+ provider.template v2.1.2

Upvotes: 2

Views: 2257

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28739

The output of the aws_subnet_ids data is a set and not a list. You would need to convert it to a list. You can achieve this with the tolist function documented here.

Your code could be updated as follows:

data "aws_subnet" "example" {
  count = length(data.aws_subnet_ids.example.ids)
  id    = tolist(data.aws_subnet_ids.example.ids)[count.index]
}

The list of subnets could then be iterated over safely within your aws_subnet data. Note a caveat however:

Pass a set value to tolist to convert it to a list. Since set elements are not ordered, the resulting list will have an undefined order that will be consistent within a particular run of Terraform.

This means that if you are accessing specific subnets, they will be reordered in the aws_subnet.example list between Terraform plan generations.

Upvotes: 3

Related Questions