Is there a way to run terraform apply for a specific tfstate file?

2.5k Views Asked by At

Is there a way to run terraform apply for a specific tfstate file? By default it takes terraform.tfstate but I need to rename it as I am managing multiple state files in azure.

Folder structure:enter image description here

2

There are 2 best solutions below

1
tomarv2 On

Yes, you can name your state file as you please if you are using Azure storage to manage your remote state:

terraform {
  backend "azurerm" {
    resource_group_name  = "<resource_group>"
    storage_account_name = "<storage_group>"
    container_name       = "<container_name>"
    key                  = "hello_world.tfstate" <-- tf state filename
  }
}

Also, check on Terraform workspaces as that be helpful to you as well.

Locally run init and plan to make sure there are no changes expected before running apply.

Push change through CI/CD pipeline to merge into main with no changes for apply to worry about.

Once you are done you can delete the older copy of the state file from storage.

5
javier On

According to the terraform apply help there is the -state flag:

-state=path Path to read and save state (unless state-out is specified). Defaults to "terraform.tfstate".

Executing:

  • terraform plan -state=yourfilename, and later
  • terraform apply -state=yourfilename;

will let you specify the state filename.

Please note, the file extension does not need to be .tfstate and you can use whatever file name.