Attach security group to multiple existing instances

Hi , we have multiple existing instances that we need to assign a new security group to. Based on Hashicorp’s documentation we tried using the for_each but that is not working . here’s snippet :

mgmt pub instances

data “aws_instance” “instance_ss1” { instance_id = “i-0b938842c166fe27b” }
data “aws_instance” “instance_ss2” { instance_id = “i-0cd19f8095f58e236” }

non-prod pvt instances

data “aws_instance” “instance_ss3” { instance_id = “i-0e39aeee6856b68d7” }
data “aws_instance” “instance_ss4” { instance_id = “i-0ec33f66a205e6229” }
data “aws_instance” “instance_ss5” { instance_id = “i-0c8defa708f2c5430” }
data “aws_instance” “instance_ss6” { instance_id = “i-0070073026edcf7ca” }

variable “mgmt_pub_instance_ids” {
type = list(string)
default = [“instance_ss1”, “instance_ss2”]
}
variable “nonprod_pvt_instance_ids” {
default = [“instance_ss3”, “instance_ss4”, “instance_ss5”, “instance_ss6”]
}

variable “mgmt” {
description = “Management VPC”
default = “vpc-0534eeff9894717dd”
}
variable “nonprod” {
description = “NonProd VPC”
default = “vpc-0a54edcdedd754146”
}

resource “aws_security_group” “on-prem-traffic” {
name = “{var.role}OnPremTraff" description = "{var.role}OnPremTraff”
vpc_id = “${var.mgmt}”

 ingress {
   from_port   = 0
   to_port     = 0
   protocol    = "-1"
   cidr_blocks = ["10.0.0.0/8", "192.0.0.0/8", "130.0.0.0/8"]
   description = "OnPrem"
 }

egress {
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = [“0.0.0.0/0”]
}

 tags = {
   Name = "${var.role}On-Prem-Traffic"
 }

}

locals {
instances = { for v in var.mgmt_pub_instance_ids : v =>v }
}

resource “aws_network_interface_sg_attachment” “sg_attachment1” {
for_each = local.instances
iname="${each.key}"
security_group_id = aws_security_group.on-prem-traffic.id
network_interface_id = data.aws_instance.mgmt_pub_instance_ids[iname].network_interface_id
}

The error we are getting is :
Error: Reference to undeclared resource

on sg_update2.tf line 83, in resource “aws_network_interface_sg_attachment” “sg_attachment1”:

83: network_interface_id = data.aws_instance.mgmt_pub_instance_ids[iname].network_interface_id

A data resource “aws_instance” “mgmt_pub_instance_ids” has not been declared

in the root module.

Error: Invalid reference

on sg_update2.tf line 83, in resource “aws_network_interface_sg_attachment” “sg_attachment1”:

83: network_interface_id = data.aws_instance.mgmt_pub_instance_ids[iname].network_interface_id

A reference to a resource type must be followed by at least one attribute

access, specifying the resource name.