CodexBloom - Programming Q&A Platform

Terraform 1.4.3: scenarios When Passing Module Outputs as Variables to Nested Module

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-08-20
terraform modules nested-modules hcl

I'm experiencing an scenario with Terraform 1.4.3 where I'm trying to pass outputs from one module as input variables to a nested module, but I'm getting an behavior that the variable isn't defined in the scope of the nested module..... My current setup includes a parent module that outputs an AMI ID, which I then want to use in a nested module to create an EC2 instance. Here's a simplified version of my code: ```hcl # main.tf (Parent Module) module "ami_output" { source = "./modules/ami" } output "ami_id" { value = module.ami_output.ami_id } module "ec2_instance" { source = "./modules/ec2" ami_id = module.ami_output.ami_id # This line throws an behavior } ``` In the nested EC2 module, I have the following: ```hcl # ec2/main.tf (Nested Module) variable "ami_id" { description = "The AMI ID to use for the EC2 instance" type = string } resource "aws_instance" "example" { ami = var.ami_id instance_type = "t2.micro" } ``` When I run `terraform apply`, I get the following behavior message: ``` behavior: Invalid value for variable at "ami_id"; must not be null. ``` I have verified that `module.ami_output.ami_id` is indeed being set in the parent module outputs, but it seems like the nested module want to access it. I’ve also tried using `terraform output` to see if the value is correctly set, and it returns the expected AMI ID. As an additional step, I attempted to directly define the variable in the nested module using a hardcoded string to see if it would create the instance, and that worked fine. This indicates that the nested module itself is functioning correctly, but the variable passing seems to be the scenario. Am I missing something in how I structure my modules, or is there a scope scenario here that I need to address? I recently upgraded to Hcl 3.10. The project is a service built with Hcl.