0
0
Terraformcloud~5 mins

Terraform state pull and push - Commands & Configuration

Choose your learning style9 modes available
Introduction
Terraform keeps track of your infrastructure in a state file. Sometimes you need to download this file to see or edit it, or upload a changed state file back to keep Terraform in sync.
When you want to back up your current infrastructure state locally.
When you need to inspect the exact resources Terraform manages.
When you want to fix a corrupted state by manually editing and uploading it.
When collaborating with a team and you want to share the latest state file.
When migrating state files between different storage backends.
Commands
This command downloads the current Terraform state from the backend and saves it to a local file named terraform.tfstate. It lets you see or edit the state safely.
Terminal
terraform state pull > terraform.tfstate
Expected OutputExpected
{ "version": 4, "terraform_version": "1.5.6", "resources": [] }
This command uploads the local terraform.tfstate file back to the Terraform backend. Use this after you have safely edited the state file to update the remote state.
Terminal
terraform state push terraform.tfstate
Expected OutputExpected
Success! Uploaded state file to the backend.
Key Concept

If you remember nothing else from this pattern, remember: terraform state pull downloads the current state file, and terraform state push uploads your local state file back to the backend.

Common Mistakes
Editing the state file without backing it up first
If the edited state file has errors, Terraform can lose track of resources causing deployment failures.
Always save a backup copy of the state file before making any manual changes.
Running terraform state push with an outdated state file
This overwrites the latest state with old data, causing Terraform to be out of sync with real infrastructure.
Always pull the latest state before editing and pushing it back.
Summary
Use 'terraform state pull > terraform.tfstate' to download the current state file locally.
Edit the local state file carefully and keep a backup before changes.
Use 'terraform state push terraform.tfstate' to upload your updated state back to the backend.