For each loops and ouput.tf files and how to get output values

hi, lets figure this:

we have 2 diferent modules, a module to create all network objct and othe r only to create EC2
and a general main to call all this modules:

:::::::::::::::::
network modules
:::::::::::::::::::
/modules/network/main.tf

resource “aws_vpc” “example” {
# One VPC for each element of var.vpcs
for_each = var.vpcs

each.value here is a value from var.vpcs

cidr_block = each.value.cidr_block
}

resource “aws_internet_gateway” “example” {
# One Internet Gateway per VPC
for_each = aws_vpc.example

each.value here is a full aws_vpc object

vpc_id = each.value.id
}

/modules/network/variables.tf

variable “vpcs” {
type = map

}

/modules/network/output.tf

output “vpc_ids” {

value = {

       for k, v in aws_vpc.example : k => v.id

      }

    }

:::::::::::::::::
Ec2 modules ( a very basic example only to his discusion
:::::::::::::::::::
/modules/ec2/main.tf

resource “aws_instance” “ec2instance” {

ami =  "ami-0d3c032f5934e1b41"
 instance_type = "t2.micro"

subnet_id = var.subnet_id

}

/modules/ec2/variables.tf

variable “subnet_id” {
type = string

}

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:::next the main file

main.tf

(:: )

provider “aws” {

profile = “”

region = local.regiao

}

variable “vpcs” {

type = map(object({

  cidr_block        = string

}))

default = {

  "PubSub1" = {

    cidr_block        = "172.26.0.0/16"

  }

  "PubSub2" = {

    cidr_block        = "172.16.13.0/24"

  }



}

}

      module "network" {

        source = "./modulos/redes"

        vpcs = var.vpcs

       

      }


      module "private_EC2" {
        source = "./modulos/ec2"
        
        
        subnet_id = "${module.network.vpc_ids}"
 
 
    
      }

question, i would like to send like a input value a list with all vpc id sent by : /modules/network/output.tf . but i don’t know how to do it.


terrafprm plan result


│ Error: Invalid value for module argument

│ on main.tf line 70, in module “private_EC2”:
│ 70: subnet_id = “${module.network.vpc_ids}”

│ The given value is not suitable for child module variable “subnet_id” defined at modulos\ec2\variables.tf:1,1-21: string required.


So how can we handle with for each and output.tf values and after how can we get each values to bu used like input parameters, to other modules.

thanks a lot

Hi @jpor1974 ,
it would really help if you edit and reformat code in your post properly.

In regards to the question, a) the EC2 module requires subnet_id instead of an vpc_id, b) the EC2 module variable subnet_id is defined as a string, but you’re passing a different data type, c) I recommend also outputting vpc_ids of the network module within the main module to understand the data structure built.