Anthony Kong
Anthony Kong

Reputation: 40654

How to pass a list of subnet to the 'subnets' attribute?

I am rewriting my subnets code to make it more flexible and driven by parameters:

resource "aws_subnet" "private" {
  count             = "${var.az_count}"
  cidr_block        = "${cidrsubnet(aws_vpc.ecs.cidr_block, 8, count.index)}"
  availability_zone = "${data.aws_availability_zones.available.names[count.index]}"
  vpc_id            = "${aws_vpc.ecs.id}"
}

This is the old code that pass the subnets to

resource "aws_ecs_service" "service" {
    network_configuration {
        subnets = [ "${aws_subnet.subnet1.id}", "${aws_subnet.subnet2.id}" ]
        ...
}

How can I pass the subnet ids from aws_subnet.private to the subnets attribute?

I have tried

subnets = ${aws_subnet.priate[*].id}

but there is an error:

 Expected the start of an expression, but found an invalid expression token

Upvotes: 0

Views: 771

Answers (1)

Kyler Middleton
Kyler Middleton

Reputation: 136

First off, you can remove the ${} except in cases where you're interpolating. Strike that stuff, and you have the much more readable:

resource "aws_subnet" "private" {
  count             = var.az_count
  cidr_block        = cidrsubnet(aws_vpc.ecs.cidr_block, 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]
  vpc_id            = aws_vpc.ecs.id
}

Your reference syntax with the splat is correct, and your spelling is wrong. Try this:

subnets = aws_subnet.private[*].id

Splat ref: https://www.terraform.io/docs/configuration/expressions.html#splat-expressions

Upvotes: 2

Related Questions