📚 Terraform Overview
This guide will help you deploy the complete AWS ECS infrastructure using Terraform (Infrastructure as Code). Terraform allows you to define, provision, and manage AWS resources using declarative configuration files.
Best for: Developers and DevOps engineers who want to automate infrastructure provisioning and manage it as code
📦 Repository: https://github.com/m-saad-siddique/terraform-aws-ecs-infrastructure
What is Terraform?
📖 Understanding Infrastructure as Code
Terraform is an open-source Infrastructure as Code (IaC) tool that enables you to safely and predictably create, change, and improve infrastructure. Instead of manually clicking through the AWS Console, you write configuration files that describe your desired infrastructure state.
Key Benefits:
- Version Control: Track infrastructure changes in Git
- Reproducibility: Deploy identical infrastructure across environments
- Automation: Provision entire infrastructure with a single command
- Collaboration: Team members can review and contribute to infrastructure changes
- Safety: Preview changes before applying them
Prerequisites
Required Tools
📦 Installation Requirements
| Tool | Version | Installation |
|---|---|---|
| Terraform | >= 1.5.0 | Download |
| AWS CLI | >= 2.0 | Download |
| Git | Latest | Download |
Install Terraform
macOS (using Homebrew):
Linux:
Verify Installation:
You should see: Terraform v1.5.7 or higher
Configure AWS Credentials
Step 1: Configure AWS Profile
Configure AWS Profile:
Terraform is configured to use the temp_resources AWS profile. Configure it using:
You’ll be prompted for:
- AWS Access Key ID: Your access key
- AWS Secret Access Key: Your secret key
- Default region:
us-east-1 - Default output format:
json
Verify AWS Profile:
This should return your AWS account ID, user ARN, and user ID.
main.tf is set to use the temp_resources profile automatically. You don’t need to set environment variables.Step 2: Verify Terraform is Using the Correct Profile
After Terraform Init, Verify Profile Usage:
You can verify Terraform is using the correct profile in several ways:
Quick Verification Script:
temp_resources profile has the necessary AWS permissions to create and manage all resources (VPC, ECS, RDS, ALB, etc.).Project Structure
📁 Terraform Directory Structure
Configuration Setup
Step 1: Copy Example Variables File
Navigate to Terraform Directory:
Copy Example File:
This creates your local variables file (already in .gitignore).
Step 2: Configure Required Variables
Open terraform.tfvars and update the following REQUIRED values:
- Never commit
terraform.tfvarsto version control - Use strong passwords for database
- Consider using AWS Secrets Manager for sensitive values in production
Initialize Terraform
Step 1: Initialize Terraform
Run Terraform Init:
This downloads required providers and modules.
Expected Output:
- ✓ Initializing provider plugins…
- ✓ Finding latest version of hashicorp/aws…
- ✓ Installing hashicorp/aws…
- ✓ Terraform has been successfully initialized!
Step 2: Validate Configuration
Validate Terraform Files:
This checks your Terraform files for syntax errors.
Step 3: Review Execution Plan
Generate Plan:
This shows what resources will be created without actually creating them.
- Check resource counts (should create ~50+ resources)
- Verify resource names match your expectations
- Confirm region and availability zones
- Note any warnings or errors
- EC2 (VPC, Subnets, Security Groups, NAT Gateways)
- IAM (Roles and Policies)
- ECR (Repositories)
- RDS (Database instances)
- ECS (Clusters, Services, Task Definitions)
- ELB (Load Balancers, Target Groups)
- CloudWatch (Log Groups)
- SSM (Parameter Store)
📦 Terraform Modules Overview
This section explains each Terraform module and what resources it creates. Modules are reusable components that encapsulate related resources.
Best for: Understanding the infrastructure components and how they’re organized in Terraform
Module Architecture
Networking Foundation
Roles & Permissions
Docker Repositories
Database
Cluster
Load Balancer
Log Groups
Parameters
Task Definitions & Services
VPC Module
📖 Module Overview
Location: modules/vpc/
Purpose: Creates the foundational networking infrastructure for all other resources.
Resources Created:
- VPC with DNS support
- 2 Public Subnets (one per AZ)
- 2 Private Subnets (one per AZ)
- Internet Gateway
- 2 NAT Gateways (one per AZ)
- Elastic IPs for NAT Gateways
- Route Tables (Public and Private)
- Route Table Associations
- Security Group for ALB
- Security Group for ECS Tasks
- Security Group for RDS
📋 Module Configuration
The VPC module is configured in main.tf:
IAM Module
📖 Module Overview
Location: modules/iam/
Purpose: Creates IAM roles with appropriate permissions for ECS tasks.
Resources Created:
- ECS Task Execution Role
- ECS Task Execution Role Policy (managed)
- ECS Task Execution SSM Policy (custom)
- Frontend Task Role
- Backend Task Role
📋 Module Configuration
ECR Module
📖 Module Overview
Location: modules/ecr/
Purpose: Creates Docker image repositories for frontend and backend.
Resources Created:
- Frontend ECR Repository
- Backend ECR Repository
- Lifecycle Policy (keeps last 10 images)
- Image Scanning Configuration
- Encryption Configuration
📋 Module Configuration
RDS Module
📖 Module Overview
Location: modules/rds/
Purpose: Creates a PostgreSQL database for the application.
Resources Created:
- DB Subnet Group
- RDS PostgreSQL Instance
- Automated Backups (7 days retention)
- Encryption at Rest
📋 Module Configuration
ECS Module
📖 Module Overview
Location: modules/ecs/
Purpose: Creates the ECS cluster for running containers.
Resources Created:
- ECS Cluster
- Container Insights (enabled)
- Fargate Capacity Providers
📋 Module Configuration
ALB Module
📖 Module Overview
Location: modules/alb/
Purpose: Creates load balancer for distributing traffic to ECS services.
Resources Created:
- Application Load Balancer
- Frontend Target Group (port 80)
- Backend Target Group (port 3001)
- HTTP Listener (port 80)
- HTTPS Listener (port 443, if certificate provided)
- Listener Rules for routing
📋 Module Configuration
CloudWatch Module
📖 Module Overview
Location: modules/cloudwatch/
Purpose: Creates log groups for ECS task logging.
Resources Created:
- CloudWatch Log Group: /ecs/frontend
- CloudWatch Log Group: /ecs/backend
- Log Retention Policy (30 days default)
📋 Module Configuration
SSM Module
📖 Module Overview
Location: modules/ssm/
Purpose: Stores configuration and secrets for ECS tasks.
Resources Created:
- /ecs/backend/DB_HOST
- /ecs/backend/DB_PORT
- /ecs/backend/DB_NAME
- /ecs/backend/DB_USER (SecureString)
- /ecs/backend/DB_PASSWORD (SecureString)
- /ecs/backend/FRONTEND_URL
- /ecs/frontend/API_URL
📋 Module Configuration
ECS Services Module
📖 Module Overview
Location: modules/ecs-services/
Purpose: Creates task definitions and ECS services for frontend and backend.
Resources Created:
- Frontend Task Definition
- Backend Task Definition
- Frontend ECS Service
- Backend ECS Service
- Auto Scaling Targets and Policies
📋 Module Configuration
⚙️ Deployment Guide
This section provides step-by-step instructions for deploying your infrastructure using Terraform.
Prerequisites: Complete Tab 1 (Getting Started) before proceeding.
Deployment Steps
Full Deployment
Step 1: Apply Terraform Configuration
Deploy Infrastructure:
Terraform will:
- Show you a plan of all resources to be created
- Ask for confirmation (type
yes) - Create all resources in the correct order
- Show outputs with important information
Verify Deployment
Step 1: View Terraform Outputs
View All Outputs:
View Specific Outputs:
Push Docker Images
Step 1: Login to ECR
Get ECR Login Token:
Step 2: Build and Push Frontend
Build and Push:
Step 3: Build and Push Backend
Build and Push:
Access Your Application
Step 1: Get ALB DNS Name
Get DNS Name:
Open the URL in your browser. The application should be accessible!
Update Infrastructure
Step 1: Modify Configuration
Edit Variables:
Modify terraform.tfvars or Terraform files as needed.
Review Changes:
Review what will change before applying.
Apply Changes:
Destroy Infrastructure
Step 1: Destroy Resources
Review Destruction Plan:
Review what will be destroyed.
Destroy Infrastructure:
Type yes to confirm.
📋 CI/CD Overview
This section covers setting up automated deployment using GitHub Actions. Once configured, every push to your main branch will automatically build Docker images, push them to ECR, and update your ECS services.
Prerequisites: All infrastructure resources must be deployed using Terraform (complete Tab 3: Deployment Guide first).
📦 Application Repositories
You need to set up CI/CD for both repositories:
- Frontend Repository: https://github.com/m-saad-siddique/frontend
- Backend Repository: https://github.com/m-saad-siddique/backend
Note: Each repository requires its own GitHub Actions workflow file and secrets configuration. The workflow process is the same for both, but with different repository names, ECR repositories, and ECS services.
CI/CD Pipeline Architecture
Code Push
Build & Deploy
Push Image
Update & Deploy
GitHub Actions CI/CD Setup
📖 Understanding GitHub Actions
GitHub Actions is a CI/CD platform that automates your software workflows. When you push code to GitHub, Actions can:
- Build: Compile your application and create Docker images
- Test: Run automated tests
- Deploy: Push images to ECR and update ECS services
Manual deployments are error-prone and time-consuming. CI/CD ensures consistent, automated deployments every time you push code – no more “it works on my machine” issues.
Important: Since your infrastructure is managed by Terraform, the ECR repositories, ECS services, and task definitions are already created. The CI/CD pipeline will only build and deploy application code, not infrastructure changes.
Step 1: Get Terraform Outputs
Get ECR Repository URLs:
You’ll need these values for the GitHub Actions workflow.
Step 2: Configure GitHub Secrets
Navigate to Repository Settings
- Go to your GitHub repository
- Click “Settings” tab
- Click “Secrets and variables” → “Actions”
Create AWS Credentials Secret
Click “New repository secret” and add:
- Name:
AWS_ACCESS_KEY_ID - Value: Your AWS access key ID
- Click “Add secret”
Add Remaining AWS Secrets
Add these AWS credential secrets (one at a time):
| Secret Name | Description |
|---|---|
AWS_SECRET_ACCESS_KEY | Your AWS secret access key |
AWS_REGION | e.g., us-east-1 |
ECR_REPOSITORY, ECS_SERVICE, or ECS_CLUSTER as secrets. These values are hardcoded in the workflow file’s env section, which is the recommended approach.🔄 How the GitHub Actions Workflow Works
The CI/CD pipeline automates the entire deployment process. Here’s how it works step by step:
- Trigger: When you push code to the
mainbranch, GitHub Actions automatically detects the change and starts the workflow. - Checkout Code: The workflow checks out your repository code to the GitHub Actions runner (a virtual machine).
- Configure AWS Credentials: Uses the AWS credentials stored in GitHub Secrets to authenticate with your AWS account.
- Login to ECR: Authenticates Docker with Amazon ECR so it can push images.
- Build Docker Image: Builds your application into a Docker image using the Dockerfile in your repository.
- Tag Image: Tags the image with the Git commit SHA (unique identifier) for version tracking.
- Push to ECR: Uploads the Docker image to your ECR repository (created by Terraform).
- Download Task Definition: Retrieves the current ECS task definition from AWS (managed by Terraform).
- Update Task Definition: Updates the task definition with the new image URI (points to the newly pushed image).
- Deploy to ECS: Updates the ECS service (created by Terraform) with the new task definition, triggering a rolling deployment.
- Wait for Stability: Waits for the new tasks to become healthy before completing.
Rolling Deployment Process:
- ECS starts new tasks with the updated image
- New tasks register with the target group and pass health checks
- ALB gradually shifts traffic from old tasks to new tasks
- Old tasks are stopped once new tasks are healthy
- This ensures zero-downtime deployments
For Frontend Repository: The workflow builds the Next.js application, pushes to the ECR repository created by Terraform, and updates the ECS service created by Terraform.
For Backend Repository: The workflow builds the Node.js/TypeScript backend, pushes to the ECR repository created by Terraform, and updates the ECS service created by Terraform.
Step 3: Create GitHub Actions Workflow
Create Workflow Directory
- In your repository root, create:
.github/workflows/ - Create file:
.github/workflows/deploy.yml
Frontend Workflow Example
For the Frontend Repository (github.com/m-saad-siddique/frontend), add this content to deploy.yml:
⚠️ Important: Replace the environment variables with values from your Terraform outputs:
Backend Workflow
For the Backend Repository (github.com/m-saad-siddique/backend), use the same workflow structure but update these environment variables:
| Environment Variable | Frontend Value | Backend Value |
|---|---|---|
ECR_REPOSITORY | frontend-repo | backend-repo |
ECS_SERVICE | ecs-production-frontend-service | ecs-production-backend-service |
ECS_TASK_DEFINITION | ecs-production-frontend-task | ecs-production-backend-task |
CONTAINER_NAME | frontend | backend-app |
Step 4: Test the Pipeline
Commit and Push
- Commit the workflow file
- Push to
mainbranch
Monitor Deployment
- Go to GitHub → “Actions” tab
- Watch the workflow run
- Check ECS Console to see service updating
📋 Workflow Execution Summary
When you push code to the Frontend Repository:
- GitHub Actions triggers the workflow
- Builds Next.js frontend application into Docker image
- Tags image with commit SHA (e.g.,
frontend-repo:abc123) - Pushes image to ECR repository (created by Terraform)
- Downloads current task definition (managed by Terraform)
- Updates task definition with new image URI
- Deploys updated task definition to ECS service (created by Terraform)
- ECS performs rolling update (starts new tasks, shifts traffic, stops old tasks)
- New frontend version is live on ALB
When you push code to the Backend Repository:
- GitHub Actions triggers the workflow
- Builds Node.js/TypeScript backend application into Docker image
- Tags image with commit SHA (e.g.,
backend-repo:xyz789) - Pushes image to ECR repository (created by Terraform)
- Downloads current task definition (managed by Terraform)
- Updates task definition with new image URI
- Deploys updated task definition to ECS service (created by Terraform)
- ECS performs rolling update (starts new tasks, shifts traffic, stops old tasks)
- New backend version is live and accessible via
/api/*routes
terraform apply.✅ CI/CD Setup Complete!
Your pipeline is now configured. Every push to main will automatically:
- Build your Docker image
- Push to ECR (repository created by Terraform)
- Update ECS service (created by Terraform) with new image
- Perform rolling deployment
Next Steps:
- Push code to
mainbranch in either repository - Monitor the deployment in GitHub Actions tab
- Verify the new version is running in ECS Console
- Test your application via the ALB DNS name (from Terraform outputs)
Optional: Terraform Infrastructure CI/CD
📖 Understanding Terraform CI/CD
You can also set up CI/CD for your Terraform infrastructure repository. This allows you to automatically apply infrastructure changes when you push Terraform code updates.
Use Cases:
- Automatically apply infrastructure changes on merge to main
- Run
terraform planon pull requests - Validate Terraform code before merging
- Maintain infrastructure as code in version control
Terraform Repository Workflow Example
Create .github/workflows/terraform.yml in your Terraform repository:
- Use
-auto-approveonly if you trust your team and review process - Consider requiring manual approval for production environments
- Use separate AWS credentials with limited permissions for CI/CD
- Enable branch protection rules on main branch
❓ Advanced Topics & Troubleshooting
This section covers advanced Terraform topics, common issues, and best practices.
Common Issues & Solutions
Terraform Errors
Error: “ResourceNotFoundException: The specified log group does not exist”
Solution: CloudWatch log groups are created automatically by the CloudWatch module. Ensure the module is applied before ECS services. If this error occurs, manually create the log groups:
Error: “CannotPullContainerError”
Solution:
- Verify Docker images are pushed to ECR
- Check ECR repository URLs in task definitions
- Ensure ECS Task Execution Role has ECR pull permissions
- Verify image tags match what’s in task definition
Error: “InvalidParameterException: The security group does not allow ingress”
Solution: Security groups are configured in the VPC module. Check that:
- ALB security group allows traffic from 0.0.0.0/0 on ports 80/443
- ECS security group allows traffic from ALB security group
- RDS security group allows traffic from ECS security group on port 5432
Error: “Insufficient capacity”
Solution:
- Try a different availability zone
- Reduce desired task count temporarily
- Wait a few minutes and retry
- Check AWS Service Health Dashboard
Best Practices
State Management
Remote State
Use Remote State: Configure S3 backend in versions.tf for team collaboration:
State Locking
Enable State Locking: Use DynamoDB table for state locking to prevent concurrent modifications.
- Never commit
*.tfstatefiles to version control - Regularly backup Terraform state files
- Use remote state for team collaboration
Security Best Practices
Secrets Management
- Never Commit Secrets: Keep
terraform.tfvarsout of version control - Use Parameter Store: Store sensitive values in AWS Systems Manager Parameter Store
- Rotate Credentials: Regularly update database passwords and access keys
- Least Privilege: IAM roles follow principle of least privilege
- Enable Encryption: All resources use encryption at rest
Cost Optimization
Cost Saving Tips
- Right-Size Resources: Start with smaller instances, scale up as needed
- Use Spot Instances: Consider FARGATE_SPOT for non-production
- Clean Up Old Images: ECR lifecycle policies automatically clean old images
- Monitor Costs: Set up AWS Cost Explorer and budgets
- Delete Unused Resources: Use
terraform destroyfor test environments
Debugging Commands
Useful Terraform Commands
State Inspection
Formatting and Validation
Complete Terraform Guide
Learn more about Rails
Learn more about Mern Stack
Learn more about DevOps
Learn more about AWS ECS Infrastructure guide


unlocker.ai – The Ultimate AI Tool for Bypassing Restrictions and Unlocking Content Seamlessly!