What is tf.state vs state locking in Terraform?

Published by halahal.in on



What is a tf.state file and what is a remote tf.state file? How to provision it? What is required? Basic Concept.

Attention to all DevOps enthusiasts, have you heard about the remote tf.state file in Terraform, which is stored in an AWS S3 bucket with all of its functions like the state lock feature?

Terraform is a very cool IaaC (Infrastructure as a Code), it lets you type your cloud infrastructure in your computer, and lets you use it multiple times with a simple command to provision or delete the whole or part of your infrastructure.
Terraform has a very essential file named tf.state file, which is used by the terraform to track the state of a particular infrastructure provisioned by the developer. Every time a new service is added or deleted from the code, it updates the information in real-time. That’s a very good feature when you are working on personal projects on your laptop but in corporate there are 10s or sometimes 100s of coders writing the infrastructure. In that case, it is not feasible for all the coders to contribute to the infrastructure because the state file or the code is in a single laptop or system.

The developer can share the code on GitHub but it will not pass on the state file to the remote repository.
Before moving ahead, I would like to share one more file or feature of Terraform that it applies the lock on the entire infrastructure for the time being the infrastructure is being provisioned or deleted by applying commands like terraform apply or terraform destroy. It prevents the duplication of changes, unless one command is completed it keeps the lock on the terraform state.
If you have provisioned an Infrastructure on AWS and have tf.state file in your local system, you can migrate it to the AWS S3 bucket and apply state locking with the help of the dynamo db table. It provides the ability to keep the infrastructure more collaborative by letting other developers or coders contribute. The Dynamo db table will apply state lock unless one user finishes with changes in the infrastructure.

This is how we will be provisioning the remote tf.state file. First, we have to create S3 and dynamo db like with the normal terraform apply command. Then we will write the terraform backend code with our S3 bucket and dynamo db table.

Categories: DevOps

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *