I have a resource A that deploys an app, and then a resource B that represents some configuration in the app. If the app gets removed outside Terraform, when a refresh occurs both resources are refreshed, even if A is removed from the state. So when B is refreshed, the provider (that I’m developing) crashes because it can’t connect to the server. Is there a way to prevent Terraform from refreshing a resource that has a destroyed dependency ? I don’t see a way to implement this in the provider of B, without undesirable side-effects at least.
Are resouce A&B from same provider?
Does resource B depends on A explicitly?
First one is a docker container and the second one from a provider I’m writting.
Yes.
I kind of feel that in the provider you are writing, you need use at least one attributes from resource A as a configuration.
This post talks about this in detail.
Yes I read this post before, the problem is not the plan phase, the resource B uses attributes of A explicitly, and the provider does not have any configuration (so no unknown attributes at config time). The problem comes during refresh, before planning: A is refreshed and marked as destroyed, but Terraform refreshes B anyway.
For now I solved the issue by having 2 separate Terraform modules.
A general rule when thinking about dependencies in Terraform is that they only ever influence the order of operations within a particular run, and don’t ever influence whether actions are taken during a run.
That can sometimes be bothersome if you have something modifying your infrastructure outside of Terraform, because Terraform’s recovery from drift is only best-effort and can’t handle all possible scenarios. You’ve seen one particularly tricky case, where the existence of one object assumes the existence of another: if Terraform had been involved in destroying these then it would’ve destroyed B first, and then A. But because things changed outside of Terraform in a way that interacts across multiple resources, the situation isn’t resolvable with Terraform alone.
I would generally say that anyone making severe changes like deleting entire objects outside of Terraform should expect Terraform to sometimes need help to recover from that. In this case, I one example of “helping Terraform” would be to tell Terraform explicitly that B is also gone, and so Terraform should “forget” about it (discard the state entry without destroying it):
terraform state rm example_thing.example
Or alternatively, if “B” would actually still exist of only “A” could be recreated first, you can ask Terraform to focus on planning only A and its dependencies, excluding B from that particular run explicitly:
terraform plan -target=another_example_thing.example
Once the user has re-achieved consistency between the Terraform state and the remote system, terraform plan
with no options should begin working again.