Terraform: create a list of subnet ids from the list of subnet indices

Viewed 62

I need to compose a list of subnet ids for load balancer. At the top level, I have variable "selected_subnets" to save the indices (i.e. not all subnets should be selected).

terraform.tfvars.json
{

  "selected_subnets": ["0", "2", "5"],

}

To refer subnet id individually, I can do.

data.aws_subnet.internal_public[count.index].id

I want to compose them into a list so that I can assign to attribute "subnets" of load balancer.

resource "aws_lb" {

  subnets = ??? /* the list of ids of all selected subnets */
1 Answers

A quick for expression will get you to the finish line:

# the list of ids of all selected subnets
[ for subnet in var.selected_subnets : data.aws_subnet.internal_public[subnet].id ]
Related