Using for_each inside Data Source (aws_instance and aws_instances)

Hi,
In the Terraform documentation I found a data source called aws_ebs_volumes and in the example they use aws_ebs_volume data source too (code below)

`data "aws_ebs_volumes" "example" {
   tags = {
     VolumeSet = "TestVolumeSet"
    }
  }

data "aws_ebs_volume" "example" {
  for_each = data.aws_ebs_volumes.example.ids
  filter {
    name   = "volume-id"
    values = [each.value]
  }
}`

The question is, can I do the same with aws_instances and aws_instance ? I have the following code

`#return all the instances that fill the paramenters (filters)
data "aws_instances" "get_instances" {
    filter {
        name = "instance-type"
        values = ["t2.micro"]
    }

filter {
    name = "availability-zone"
    values = ["sa-east-1a"]
}

instance_state_names = ["running", "stopped"]
}

#return the data of one specific insntace
data "aws_instance" "get_specific_instance" {
    for_each = "${data.aws_instances.get_instances.ids}"

   filter {
    name = "tag:Name"
    values = ["PocTerraform", "Application"]
  }
}`

but it doesn’t work, is it just syntax errors or it’s not possible to do it?
Thanks in advance

Hi @FranciscoJLucca,

What error messages did you see when you tried this?

The error is this one:

Error: Your query returned more than one result. Please try a more specific search criteria.

  on main.tf line 24, in data "aws_instance" "get_specific_instance":
  24: data "aws_instance" "get_specific_instance" {

Just updating the code, I used a toset function otherwise I was getting other error:

Error: Invalid for_each argument

  on main.tf line 25, in data "aws_instance" "get_specific_instance":
  25:     for_each = data.aws_instances.get_instances.ids

Your data "aws_instance" "get_specific_instance" block doesn’t seem to actually constrain the result by the id you looked up.

I think to get the result you wanted here you’ll need to replace the filter block with an instance_id argument:

data "aws_instance" "get_specific_instance" {
  for_each = toset(data.aws_instances.get_instances.ids)

  instance_id = each.value
}