Home > Software engineering >  How to grab two arbitrary subnet IDs from Terraform
How to grab two arbitrary subnet IDs from Terraform

Time:09-02

Looking to deploy a Fargate application where the invoking function runs the ECS container in two arbitrarily selected subnets from the default VPC.

So far my template looks like this:

data "aws_subnets" "subnets" {
  filter {
    name   = "vpc-id"
    values = [var.vpc_id]
  }
}

data "aws_subnet" "subnet" {
  for_each = toset(data.aws_subnets.subnets.ids)
  id       = each.value
}

resource "aws_lambda_function" "ecs_invoker" {
  function_name = "ecs_invoker"
  ...
  environment {
    variables = {
      SUBNET_PRIMARY = data.aws_subnet.subnet[0]
      SUBNET_SECONDARY = data.aws_subnet.subnet[1]
    }
  }
}

However, this produces the following error:

│ Error: Invalid index
│
│   on lambda.tf line 16, in resource "aws_lambda_function" "ecs_invoker":
│   16:       SUBNET_PRIMARY = data.aws_subnet.subnet[0]
│     ├────────────────
│     │ data.aws_subnet.subnet is object with 6 attributes
│
│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name, not by numeric index.
╵

So how exactly should I grab two arbitrary subnet IDs from the default VPC?

CodePudding user response:

Since you used for_each, data.aws_subnet.subnet will be a map, not a list. So to get two first subnet ids, you can do:

SUBNET_PRIMARY = values(data.aws_subnet.subnet)[0].id
SUBNET_SECONDARY = values(data.aws_subnet.subnet)[1].id

To get two random ids, you can do:

resource "random_shuffle" "subnets" {
  input        = values(data.aws_subnet.subnet)[*].id
  result_count = 2
}

and then

SUBNET_PRIMARY = random_shuffle.subnets.result[0]
SUBNET_SECONDARY = random_shuffle.subnets.result[1]
  • Related