I am not getting output from ec2 when I create multiple ec2

I need to crate multiple ec2 one in each subnet. so I am looping through it creating like this

for_each = var.subnets ( subnets is a list having two subnets)
ami
sg

output

output “instance_id” {
description = “The ID of the instance”
value = try(aws_instance.this[0].id, “”)
}
It does not display anything just “”

if I changed the subnet to single string and outputs like this

output “instance_id” {
description = “The ID of the instance”
value = try(aws_instance.this.id, “”)

}

I get instance id

Appreciate your help

Please show your full Terraform code, I think you have edited it down too much, to the point where it is too hard to reason about the problem.

Here are all, var, code, outputs and error
main.tf
variable “AWS_REGION” {
default = “us-east-1”
}

variable “subnets” {
type = map(string) #list(string)
description = “A list of subnet IDs to associate with NLB”

default ={subnet = “subnet-xxxxxxxx”
subnet2 = “subnet-xxxxxxxx”
}
}

resource “aws_instance” “this” {
for_each = toset(var.subnets2)
ami = “ami-0533f2ba8a1995cf9”
instance_type = “t2.micro”
key_name = “test_key”

subnet_id = each.value #“subnet-xxxxxxxx” #each.value #aws_subnet.some_public_subnet.id

}

outputs.tf

####This does not work. should work in case of multiple ec2
/*
output “instance_id” {
description = “The ID of the instance”
value = aws_instance.this[*].id
}

*/

This works on both single or multiple ec2 and display ec2 details.

output “ec2_instances2” {
value = “${aws_instance.this}”
}

This is not working. should work in case of multiple ec2

/*
output “ec2_ids” {
value = “${aws_instance.this[*].id}”
}

output “ec2_private_ips” {
value = “${aws_instance.this[*].private_ip}”
}
*/

Here are the error

Case 1


│ on ec2.tf line 23, in output “ec2_ids”:
│ 23: value = “${aws_instance.this[*].id}”

│ This object does not have an attribute named “id”.

Case 2

│ Error: Invalid index

│ on ec2.tf line 20, in output “instance_id2”:
│ 20: value = aws_instance.this[0].id
│ ├────────────────
│ │ aws_instance.this is object with 2 attributes

│ The given key does not identify an element in this collection value. An object only supports looking up attributes by name, not by numeric index

Case 3

[root@localhost ec2]# terraform apply

│ Error: Unsupported attribute

│ on ec2.tf line 15, in output “instance_id”:
│ 15: value = aws_instance.this[*].id

│ This object does not have an attribute named “id”.

Your message is hard to read because all the indentation has been lost, and various lines have turned into headings, because the message is interpreted as Markdown syntax.

Please edit it to use code blocks (write ``` on a line by itself to start and finish a block), so that you don’t make things hard for the person reading it.