Storing state files using AWS S3 and DynamoDB.
1. Importance of Terraform state file
The Terraform state file is a JSON record of infrastructure resources managed by Terraform. It tracks resource IDs, properties, and dependencies. Stored in a remote backend for collaboration, the state file ensures consistency and prevents conflicts with locking. It contains sensitive data and requires secure storage. Regular backups and disaster recovery measures are advised. Updating the state file with “terraform apply” keeps it synchronized with infrastructure changes. It’s vital for accurate resource management, maintaining integrity, and facilitating collaboration in Terraform workflows.
The state file serves several important purposes:
- Tracking and Recording
- Dependency Management
- Concurrency and Collaboration
- Infrastructure Updates
- Resource Deletion
2. Storing State files on Amazon S3 Bucket
STEP 1: Create an Instance, IAM User and Install Terraform
Create an Instance, IAM user, login into the console and install the terraform by following the steps which I published on Terra week Day 3 (Follow step 1 to step 4)
https://link.medium.com/7oM8vvf0sAb
STEP 2: Make Working Directory and create terraform.tf and resource.tf file
Create a terraform.tf file
mkdir terra
cd terra
vi terraform.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.67.0"
}
}
}
Create a resource.tf file
resource "aws_s3_bucket" "my_s3_bucket" {
bucket = "terraweek123"
}
resource "aws_dynamodb_table" "my_dynamo_table" {
name = "terraweek-demo"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
terraform init
terraform validate
terraform plan
terraform apply
we created S3 Bucket to Store the Statefile and Dynamo DB to create a LockID
STEP 3: Create a new Directory and backend the state file to DynamoDB
mkdir dynamoDB
cd dynamoDB
vi terraform.tf
vi terraform.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.67.0"
}
}
backend "s3" {
bucket = "terraweek123"
key = "terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraweek-demo"
}
}
Thank you shubhamlondhe , for the wonderful session
#devops #terraweek #terraform #hcl #aws
I’m actively searching for new opportunities and eager to broaden my professional network.
Linkedin : https://www.linkedin.com/in/raj-kumar-devops/
Website : https://bento.me/rajdevops
For more Projects : https://medium.com/@rajdevops