This task focuses on setting up remote state management using either Terraform Cloud or an S3 backend with DynamoDB for state locking. It ensures that infrastructure state files are centrally managed, secure, and versioned to prevent conflicts during concurrent deployments.
terraform {
cloud {
organization = "my-terraform-org"
workspaces {
name = "my-infra-workspace"
}
}
}
terraform login
terraform init
Terraform state:
aws s3 mb s3://my-terraform-state-bucket --region us-east-1
aws s3api put-bucket-versioning --bucket my-terraform-state-bucket --versioning-configuration Status=Enabled
aws dynamodb create-table \
--table-name terraform-lock \
--attribute-definitions AttributeName=LockID,AttributeType=S \
--key-schema AttributeName=LockID,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-lock"
}
}
terraform init
Now that remote state management is set up, define Terraform configurations for AWS infrastructure:
Example: Deploy an EC2 Instance
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-12345678"
instance_type = "t2.micro"
tags = {
Name = "Terraform-EC2"
}
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::my-terraform-state-bucket",
"arn:aws:s3:::my-terraform-state-bucket/*"
]
},
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:DeleteItem",
"dynamodb:Scan"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/terraform-lock"
}
]
}
terraform plan
terraform apply -auto-approve
terraform plan
If another user tries to apply changes at the same time, Terraform will show a lock error.
name: Terraform CI/CD
on:
push:
branches:
- main
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v2
- name: Setup Terraform
uses: hashicorp/setup-terraform@v1
- name: Terraform Init
run: terraform init
- name: Terraform Plan
run: terraform plan
- name: Terraform Apply
if: github.ref == 'refs/heads/main'
run: terraform apply -auto-approve
aws dynamodb scan --table-name terraform-lock
tfsec
.By implementing Terraform Cloud or S3 backend with DynamoDB, we ensure that the Terraform state is secure, locked, and versioned, preventing conflicts in multi-user environments. This setup enhances collaboration and stability in AWS infrastructure automation.