Get an element from a list Terraform

Viewed 4382

I have a small question about Terraform but I can't find a solution online. Imagine the following scenario:

data "aws_vpc" "vpc_name" {
  id = var.vpc_id
}

data "aws_subnet_ids" "vpc_subnets" {
  vpc_id = data.aws_vpc.vpc_name.id
}

And imagine I create an EC2 instance like this:

resource "aws_instance" "ec2_test" {
  ...
  ami                  = ...
  instance_type        = ...
  subnet_id            = element(tolist(data.aws_subnet_ids.vpc_subnets.ids), 1)
  ...

In the subnet, I have selected an element using the element function and converted the list of subnet ids to a list.

Now, I have two questions:

  1. Is it possible to select the first subnet without doing the conversion to list (tolist)? I wonder why I can do something like data.aws_subnet_ids.vpc_subnets[1] or something like that?

  2. How can I retrieve a random id from the list of subnets?

Regards,

1 Answers

You need the tolist operation, because aws_subnet_ids.ids is a set. You could clean it up a little and say tolist(data.aws_subnet_ids.vpc_subnets.ids)[0].

To get a random number, use the random provider.

Related