Can I use same state file in terraform for multiple terraform files

terraform

Suppose in project directory I have 2 .tf files and I want to have same state file for both .tf file. Now if execute plan for one .tf file my state file got updated but when I am trying to execute plan for other .tf file my state file got updated with latest file and it destroy the previous.tf files resources

Best Answer

Its not really clear what you're trying to accomplish - perhaps you could clarify?

If you have multiple files in directory, Terraform should plan and apply both of them against the same state file (using the Backend declaration). As the doc says:

"Terraform loads all configuration files within the directory specified in alphabetical order. The configuration within the loaded files are appended to each other. This is in contrast to being merged."

If you wanted to keep the .tf files separate, you could run Terraform from different directories (thus creating multiple state files) or alternatively, use Workspaces.

You can have multiple workspaces tied to a single backend (or state). This allows multiple distinct instances of that configuration to be deployed. These previously were referred to as "environments" but this was renamed in 0.10.

From the document:

Named workspaces allow conveniently switching between multiple instances of a single configuration within its single backend. A common use for multiple workspaces is to create a parallel, distinct copy of a set of infrastructure in order to test a set of changes before modifying the main production infrastructure.

To use a workspace, you would run the command like this:

$ terraform workspace new bar
Created and switched to workspace "bar"!

You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.

Then you can reference workspace interpolation within your resources to dynamically alter what is deployed:

resource "aws_instance" "example" {
  count = "${terraform.workspace == "default" ? 5 : 1}"

  # ... other arguments
}