How to define/ control dependencies on resources created with for_each

Hi

We have some VMs built using a centralised module which creates the VM, assigns a public IP, creates / assigns a NIC and associated NSG. Outputs from this module have been used to create extensions and alerts

The module used count to decide whether to create the resources, and how many. However, there is a requirement to regularly destroy each of the VMs in turn, to take advantage of the fact that Microsoft patch their base images on patch Tuesday, rather than deploying Windows Updates.

Leaving aside questions about the viability of that :slightly_smiling_face: I know that count causes a problem there because it won’t like index 0 being destroyed. I’ve therefore used for_each to iterate over a list of the VM names to create them so the indices can be uniquely named and referred to, which works fine as far as it goes.

However, the extensions are more of a problem (at least, the way I’m trying to do them at the moment). I’ve used local variables and for loops to iterate over the same list of VM names as used by the VM module, then used that to address the object entries and their outputs from the VM module and build a local object with the VM names and resource IDs, which I then use to finally iterate over these with for_each to create the extensions for each VM.

When I plan the destroy for one of the VMs, that’s fine, it just plans to destroy the designated VM; however, it also wants to destroy all of the extensions for both VMs, so there are obviously some dependencies there that I’m not accounting for, which would lead into additional issues.

I wondered if the list type outputs’ indices might be causing an issue, despite the work I’ve done to break those out into a locals object, so I’ve even taken that module out of the equation and used the resources directly; however, targeted destroy of one of the two VMs still insists on planning destruction of the extensions for both VMs

I can post some examples of the code if required … just wondered if anyone has come across this before and how to not only get around it, but properly plan for the dependencies created so I can improve my code going forward

Thanks in advance for anyone who can offer any guidance