Remote State Management in Terraform via GCP/AWS

Ayush Kumar singh
3 min readJun 5, 2021

What is Terraform State, and How Terraform manages it?

When we configure or automate any resource terraform, create a state file where it stores all the changes. So that next time when we try to modify or destroy the resource. It must know what we already have.

This state file is stored by default in a local file named “terraform.tfstate”. in JSON Format.

State file will be created during ‘terraform apply,’ and it will be updated every time we modify the resources. When we modify the resource a new object is created and compared with the state file object. Then the previous object is deleted, and the new one gets mapped to the state file. Thus every time we update a resource, we’re also creating a new remote object.

This State will store Not only the Changes but also tracks resource dependencies. And when we hit ‘Terraform destroy,’ it helps determine the order in which the resources should be destroyed.

Can 2 people change Terraform State simultaneously?

No, when we hit ‘terraform apply,’ the State file gets locked and can’t be modified at the same time. The next user has to wait till the first one completes. This is a Default Feature of Terraform.

Why Remote State Management?

By default, Terraform stores state locally in a file named terraform.tfstate.
When working in a team it gets difficult to manage the state as each user must make sure they always have the latest state data before running Terraform, and nobody else runs Terraform at the same time.

This issue can be resolved by maintaining the state file on Remote Data Center/Cloud Server and shared between all team members.

State Management on Google Cloud Storage:

  1. create a GSC bucket. Enable versioning to prevent loss.

2. Authenticate with GCP and Add backend.

Done. Now ‘Terraform init’ and Our Remote backend is configured.

We Can Also Use AWS S3 and other Clouds for Remote State management. Check the full list here.

Output Of Terraform Init when Backed Is Configured :

State Locked Output :

It Even Shows Who is Currently working on the state, the time, other details.

Google Cloud Storage :

Note: If an error persisting the state to the backend, Terraform will write the state locally. This is to prevent data loss. If this happens, the end-user must manually push the state to the remote backend once the error is resolved.

Push State manually : terraform state push
terraform does not recommend pushing the state Manually.

Thanks For Reading 🙏

Connect With Me:
LinkedIn: Here

--

--