Missing Resource Instance Key

Hey Terraform Community,

I’m reaching out for help with an error that’s been blocking my progress for a while now. I’m running into a “Missing Resource Instance Key” error when trying to deploy my infrastructure using Terraform.

Here’s a detailed breakdown of what I’m experiencing and what I’ve tried so far.

I’m using Terraform to manage a set of AWS resources. Here’s a snippet of my configuration:

locals {
  security_groups = {
    sg_ping   = aws_security_group.sg_ping.id,
    sg_8080   = aws_security_group.sg_8080.id,
  }
}

resource "aws_instance" "web_app" {
  for_each               = local.security_groups
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = "t2.micro"
  vpc_security_group_ids = [each.value]
  tags = {
    Name = "${var.name}-learn-${each.key}"
  }
}

When running terraform apply, I get the following error:

Error: Missing Resource Instance Key

  on main.tf line 23, in resource "aws_instance" "web_app":
  23:   vpc_security_group_ids = [each.value]
    |----------------
    | each.value is tuple with 2 elements

The given key does not identify an element in this collection value.

When I search about this I came across resources/articles Devops engineer skills Terraform error because data block output returns Missing resource instance key, as per them, I am using correct syntax: each.key and each.value. I reviewed the Terraform documentation on using for_each with resources. I followed examples to ensure my implementation aligns with the recommended practices. But didn’t get any solution.

Kindly help me to get out of this.

Thanks

Hi @elbertelena95

What you have looks reasonable. It seems you are trying to deploy 2x aws_instance.webapp resources, one for each aws_security_group referenced by your local.

For some further information, can you post the output of the following two commands run within terraform console

> type(local.security_groups)
> local.security_groups

Which will show us the type of the full local.security_group object and also the content that the subsequent for_each is trying to iterate over.

Thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.