Day 4 of #30daysofawsterraform challenge
Today I come across "Terraform state file" & created remote backend of state file in s3 bucket. Simple explanation of the topics
$ What is Terraform state files:
It is a local or remote file that Terraform uses to remember the real infrastructure it created, map it to your config, and track changes.
If we want to modify any information, terraform will compare its configuration file with actual AWS environment with the help of "state file"
$ Location of state file:
- Inside working directory >> $ls -ltra >> locate "terraform.tfstate"
- It is in JSON format.
$How remote backend works:
- Storing "terraform.tfstate" remotely like s3 bucket, Azure blob, GCP cloud storage as remote backend.
- Then every time we run terraform apply command check the state in "terraform.tfstate" in s3 bucket and compare it with actual infra.
$ Configure Terraform Remote Backend: (See the images)
State_file.tf:
Run:
$terraform init
$terraform plan
$terraform apply
§ Best practices:
- Store state file to remote backend in cloud storage.
- Use state locking
- Do not update/delete the file manually.
- Isolation of your state file based on environment
- Regular backup of state file
New concept I explored:
Terraform state lock:
- State locking ensures that only one Terraform operation (plan, apply, destroy) can modify the state at a time.
- Simply. the process in which your telling terraform that once the terraform file is used by a process, do not use it elsewhere.
- It will lock the terraform state file and once process is completed then release the lock file.
- Earlier used dynamo DB for state locking, now it's s3
Eg:
Imagine 2 engineers running terraform apply at the same time:
User1 -----terraform apply-----> updating state
User2 -----terraform apply-----> updating state ❌ (conflict!)
a. Without locking, both may write at once → corrupted .tfstate ❗
b. With locking, Terraform will block the second operation until the first completes.
Devops #Terraform #AWS
Thanks to Piyush sachdeva The CloudOps Community


Top comments (0)