CodexBloom - Programming Q&A Platform

Terraform: implementing Using `for_each` to Create Multiple EC2 Instances with Different Attributes

👀 Views: 1384 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
terraform aws ec2 HCL

I'm getting frustrated with I'm learning this framework and I've spent hours debugging this and I've looked through the documentation and I'm still confused about I'm having trouble using `for_each` to create multiple EC2 instances in Terraform where each instance has different attributes... I defined a map of instance configurations but am working with an behavior during the apply phase. Here's my current configuration: ```hcl variable "instances" { type = map(object({ ami = string instance_type = string tags = map(string) })) default = { "web" = { ami = "ami-0abcdef1234567890" instance_type = "t2.micro" tags = { Name = "web-server" } }, "db" = { ami = "ami-0abcdef1234567890" instance_type = "t2.medium" tags = { Name = "db-server" } } } } resource "aws_instance" "app" { for_each = var.instances ami = each.value.ami instance_type = each.value.instance_type tags = each.value.tags } ``` When I run `terraform apply`, I get the following behavior message: ``` behavior: Invalid function argument on main.tf line 16, in resource "aws_instance" "app": 16: tags = each.value.tags Invalid value for "tags": expected a map of strings, got: string. ``` This behavior indicates that the tags are not being processed as I expect. I tried wrapping `each.value.tags` in a `merge` function, but that didn't resolve the scenario. The `tags` argument is defined as a map in the variable, so I'm not sure where I'm going wrong. Additionally, I've checked the Terraform version (1.4.0) and the AWS provider version (4.0.0) to ensure compatibility. Has anyone encountered this question before or have suggestions on how to properly configure the `for_each` with different instance attributes? Is this even possible? I'm working with Hcl in a Docker container on macOS. What are your experiences with this?