Dependencies and for_each - depending on a single instance rather than the entire resource to prevent dependency loops?

I was having issues with a module (the AWS ECS module) where when I deleted something, it would always end up with a dependency loop. It didn’t make much sense to me until I started diving into the state file, and I discovered that the state file doesn’t list dependencies the way I expected:

When you have two related resources that depend on eachother, for example an AWS launch template and an AWS autoscaling group, and you want to make a set of them, it’s natural to have something like this:

resource "aws_launch_template" "my_lt" {
  for_each = local.node_groups
  ...
}

resource "aws_autoscaling_group" "mt_asg" {
  for_each = local.node_groups
  launch_template = aws_launch_template.my_lt[each.key].id
}

The goal would be for each ASG to depend on its matching launch template, but not any other LTs. However this is not what happens: each instance of the ASG says that it depends on “aws_launch.template.lt” - and in fact it does seem to depend on all the launch templates, not just the one it should be matched up with.

This makes it very difficult to tear down some of the resource pairs (by removing elements from local.node_groups) because the dependency chain seems to always result in a dependency loop.

Is this something that terraform 13 will fix? Or are there other ways to get the dependencies to be more specific?

Rezzing an old thread, but why not

resource "aws_launch_template" "my_lt" {
  for_each = local.node_groups
  ...
}

resource "aws_autoscaling_group" "mt_asg" {
  for_each = aws_launch_template.my_lt
  launch_template = each.value.id
  ...
}

This way you created a launch template for each node group, and an ASG for each launch template. Terraform should (I haven’t confirmed) be able to understand the 1:1 relationship between you launch templates and ASGs.

That is not how Terraform works. You can use the terraform graph command to display a visualisation of the dependency graph as Terraform understands it. You’ll find that the nodes of the graph only mention entire blocks - individual elements of a for_each aren’t evaluated until after all dependency processing is already done.