Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Terraform: use output of one module in another module

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

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. You’re just assigning an array to a field that expects an array:

resource "aws_ecs_service" "foo" {
  name = "foo"
  ...
  network_configuration {
    ...
    subnets = var.public_subnet_ids
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading