The correct way to use Terraform is to ensure that each configuration has a different remote state configuration so that the state snapshots for each are separated. If you configure two configurations with the same state location then, as you’ve seen, they will each try to undo each others’ work because Terraform’s job is to compare the configuration to the most recent state snapshot and identify a set of operations to make the state (and associated remote objects) match the configuration.
If you have objects managed by one configuration that you need to use in another configuration, you can use data sources, which are a special kind of resource that reads an existing object managed elsewhere rather than managing a new object.
An easy data source to get started with, assuming that those running Terraform will have access to all of the state snapshots across all the configurations, is
terraform_remote_state which allows one configuration to read the outputs from another configuration directly from its latest state snapshot.
Note that when Terraform is managing objects (
resource blocks rather than
data blocks) it expects that only one Terraform configuration is managing each object and that no non-Terraform system will make changes to that object. If you try to manage the same object from two configurations – for example, by using
terraform import to forcefully associate an existing object managed elsewhere with a resource in your current configuration – the two Terraform configurations will once again try to undo each others’ work, because they each expect that they are exclusively managing that object.
For that reason, an important part of designing your Terraform configurations architecture is deciding which objects are managed by which decomposed part of your system, which will then affect how data flows between configurations using data sources.