'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
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 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dan Monego |