Terraform state file on s3 backend
Terraform state file -
- When you are building an infrastructure with terraform config, a state file gets generated locally in the directory called "terraform.tfstate" .
- The state file contains information of the infrastructure and configuration which are created.
- It also helps to modify or manage the infrastructure.
- We can also say that , it acts as a memory for the infrastructure created , so that we can make the changes afterwards.
When working on a team, it is better to store this state file remotely so that more folks can access it to make changes to the infrastructure.
When working with Terraform in a team, use of a local file makes Terraform usage complicated because each user must make sure they always have the latest state data before running Terraform and make sure that nobody else runs Terraform at the same time.
With remote state, Terraform writes the state data to a remote data store, which can then be shared between all members of a team. Terraform supports storing state in Terraform Cloud, HashiCorp Consul, Amazon S3, Azure Blob Storage, Google Cloud Storage, Alibaba Cloud OSS, and more.
Prerequisite-
- s3 storage
- DynamoDB Table
To setup the terraform state file in s3 backend , first we need to create the s3 bucket and then s3_backend.
Lets starts form creating s3 bucket through terraform -
Locking state file -
DynamoDB table provide the mechanism of "lock" for our state file.
Why do we need Locking.....??
As we store our state file in remote location (s3 Bucket) so that many people can access it , which create a risk for multiple people attempting to make change to same file which can cause damage or data loss, this condition known as Race Condition.
That is why we need to lock our state file.
So now create a DynamoDB table for locking the state file -
After creating both the resources (i.e. s3 bucket and DynamoDB table) , we have to modify our terraform s3 backend while adding bucket_name and table_name .
Note:- Before running the s3 backend script , we have to first create the two resources (i.e. s3 bucket and DynamoDB table)
Now we can initialize the script -
terraform init
terraform validate
terraform plan
terraform apply
At last we can initialize our s3 backend script -
terraform init
So lets first checkout our s3 bucket -
Here you can see our state file is working fine in s3 and if you check your terraform.tfstate file locally, you will find that it is now become empty.
Now lets check our DynamoDB table -
SETUP COMPLETE !!
For the code , refer to my GitHub repo
Lecturer | DevOps Engineer
3 年Thanks for writing such a great article
Solutions Consultant | Pre-Sales
4 年Great article Sanjay!