The "for_each" set includes values derived from resource attributes that

ok i’ve read through all the other threads that come up on this and i’m a bit stuck.

my code is really simple, and looks like this:

data "aws_instances" "servers" {
  instance_tags = {
    "Owner": var.username
    "Purpose": "xxx-poc"
  }

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

data "aws_instance" "items" {
  for_each = data.aws_instances.servers.ids
  instance_id = each.key
}

this actually worked, then i restarted my machine and i got the famous

The “for_each” set includes values derived from resource attributes that

so as i understand it the error is because it needs an index for for_each that is known at compile time.

that’s pretty limiting no?

even the alternative of using the -target option seems to against the idea of a press-button-configure setup…

should i actually be reading out these values from my tfstate using terraform_remote_state instead as the top note here seems to suggest?

i tried configuring this to work with a local file, but it wouldnt pick it up.

quite a lot more mental juggling than when using Ansible. though i appreciate the power of Terraform’s type safety and graph engine.

Hi @calvinc,

It seems that something in your configuration is blocking Terraform from querying the instances during the planning phase, and so Terraform doesn’t know which instances of aws_instance.items you are trying to query.

I’m not sure why that is from only the information given here, but the following are two common reasons:

  • var.username has a value that isn’t known during planning, so that data source doesn’t know what query to send. (This would be possible only if this is a nested module and if that variable is being assigned from a resource attribute that won’t be known until the apply step)
  • aws_instances.servers itself depends on something that has changes pending, and so Terraform wants to wait until the apply step to ensure that it’s fetching the most up-to-date set of instances.

Terraform should typically explain itself at least a little in the output produced alongside this error message. Specifically, I would expect it to announce that the first data source needs to be deferred to the apply phase, and then in parentheses give a hint as to why that is true, such as “because it depends on other resources with changes pending” (which would match the second possibility I described above).

If we can determine more specifically what’s going on here then we may be able to find a different way to explain this situation to Terraform so that it can better understand the relationships between all of these resources.