CodexBloom - Programming Q&A Platform

Terraform Variable Inheritance guide with AWS EC2 Instance Modules

👀 Views: 99 💬 Answers: 1 📅 Created: 2025-07-04
terraform aws modules HCL

I'm updating my dependencies and I'm sure I'm missing something obvious here, but I'm working with a question with variable inheritance in my Terraform configurations when using modules for AWS EC2 instances... My main configuration file uses a local variable to define some metadata, but it seems that this local variable is not being passed correctly to the child module for the EC2 instances. Here’s how I've set it up: In my `main.tf`, I have defined a local variable: ```hcl locals { instance_tags = { Name = "MyInstance" Environment = "Production" } } ``` Then I'm calling the EC2 module like this: ```hcl module "ec2_instance" { source = "./modules/ec2_instance" tags = local.instance_tags } ``` Inside my `ec2_instance` module, I'm trying to access the `tags` variable: ```hcl variable "tags" { type = map(string) } resource "aws_instance" "my_instance" { ami = "ami-12345678" instance_type = "t2.micro" tags = var.tags } ``` However, when I run `terraform apply`, I'm getting the following behavior: ``` behavior: Invalid function argument on modules/ec2_instance/main.tf line 12, in resource "aws_instance" "my_instance": 12: tags = var.tags Invalid value for variable "tags": Expected a map of string, got string instead. ``` I’ve confirmed that `local.instance_tags` is indeed a map, but Terraform seems to think it’s a string. I’ve also tried explicitly defining the variable type as `any` in the module, but it didn’t resolve the scenario. I’ve checked the Terraform version I'm using, which is 1.3.7. Any insights on how to properly pass this local variable into the module? Are there any nuances with variable handling in Terraform modules that I might be missing? This is part of a larger application I'm building. Am I missing something obvious? Any feedback is welcome!