0

I have a module called vpc and another module called ecs. I'm trying to reference the AWS subnets created in the vpc module in ecs. Here's what I have, so far:

main.tf

module "ecs" {
  source = "./service/ecs"
  public_subnet_ids = module.vpc.ecs-public-subnet.ids
}

vpc.tf

resource "aws_subnet" "public-subnet-1" {
...
}
resource "aws_subnet" "public-subnet-2" {
...
}
output "ecs-public-subnet" {
  value = [
    aws_subnet.public-subnet-1.id,
    aws_subnet.public-subnet-2.id
}

ecs.tf

variable "public_subnet_ids" {
  type = list(string)
  description = "public subnets"
}

resource "aws_ecs_service" "foo" {
  name = "foo"
  ...
  network_configuration {
    ...
    subnets = ["${element(var.public_subnet_ids, count.index)}"]

When I execute plan, I get the following:

Error: Reference to "count" in non-counted context The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set.

Terraform version 1.1.8, aws provider version 4.10.0

I'm totally happy with changing the entire approach, if there is a better way to do this.

1 Answer 1

2

count is used when you're using a block that's meant to make multiple resources. Think of it as like the index of a loop. What you're doing is simpler and easier - you're assigning an array to a field that takes an array.

First, just reference your array in the module definition. .ids is not valid:

module "ecs" {
  source = "./service/ecs"
  public_subnet_ids = module.vpc.ecs-public-subnet
}

Next, you can just reference the same array inside your module:

resource "aws_ecs_service" "foo" {
  name = "foo"
  ...
  network_configuration {
    ...
    subnets = var.public_subnet_ids
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.