Advertisement
Intermediate Time: 3–4 weeks IT & Networking

Cloud Infrastructure with Terraform

Build and manage complete cloud infrastructure using Terraform with modules, state management, multi-environment, and CI/CD integration.

TerraformIaCAWSCloudDevOpsInfrastructure as Code
DifficultyIntermediate
Duration3–4 weeks
Components10 items
Steps6 steps

Introduction

Build and manage complete cloud infrastructure using Terraform with modules, state management, multi-environment, and CI/CD integration. This comprehensive guide covers everything from design through implementation, testing, and deployment.

Theory & Background

Terraform: declarative IaC (describe desired state, not steps to get there). Provider: plugin for each cloud/service (AWS, GCP, Azure, Kubernetes, Datadog). Resource: each cloud object (aws_instance, aws_s3_bucket, aws_rds_cluster). Data sources: read existing resources not managed by Terraform. State file: tracks actual deployed resources to detect drift. Plan: shows what will change before applying. Apply: makes changes. Destroy: remove all resources. Never modify state file manually.

Advertisement

Components & Requirements

10 components required for this project.

#ComponentPurposeQty
1Terraform CLI 1.6+Infrastructure provisioning toolx1
2AWS Account or GCP/AzureCloud providerx1
3AWS CLICloud provider authenticationx1
4Terraform Cloud (free tier)State backend and team collaborationx1
5VS Code + HashiCorp extensionTerraform development environmentx1
6tfsec / checkovTerraform security scanningx1
7Terratest (Go)Infrastructure testing frameworkx1
8pre-commit hooksTerraform format and validationx1
9GitHub ActionsTerraform plan/apply in CI/CDx1
10AWS Cost ExplorerInfrastructure cost monitoringx1

Step-by-Step Implementation

Follow these 6 steps carefully.

1
Terraform Architecture and Concepts

Terraform: declarative IaC (describe desired state, not steps to get there). Provider: plugin for each cloud/service (AWS, GCP, Azure, Kubernetes, Datadog). Resource: each cloud object (aws_instance, aws_s3_bucket, aws_rds_cluster). Data sources: read existing resources not managed by Terraform. State file: tracks actual deployed resources to detect drift. Plan: shows what will change before applying. Apply: makes changes. Destroy: remove all resources. Never modify state file manually.

2
VPC and Network Infrastructure

Create a complete AWS VPC: CIDR 10.0.0.0/16. Public subnets (10.0.1.0/24, 10.0.2.0/24) in 2 AZs — for load balancers, NAT gateways. Private subnets (10.0.11.0/24, 10.0.12.0/24) — for EC2 instances, ECS tasks. Database subnets (10.0.21.0/24, 10.0.22.0/24) — for RDS, isolated from internet. Internet Gateway for public subnets. NAT Gateway for private subnets (outbound internet access). Route tables configured appropriately. Terraform modules encapsulate this for reuse.

3
ECS Fargate Application Deployment

ECS Fargate: serverless containers — no EC2 to manage. Define task definition: container image, CPU (256 units = 0.25 vCPU), memory (512 MB), port mapping, environment variables from Parameter Store, logging to CloudWatch. ECS Service: maintain 2 running tasks, ALB health check integration, auto-scaling based on CPU/request count. ALB: distribute traffic across ECS tasks, SSL termination with ACM certificate, health checks at /health endpoint.

4
RDS Database and Secrets Management

RDS PostgreSQL Multi-AZ deployment: primary in AZ1, standby replica in AZ2 (automatic failover). db.t3.medium instance. Encrypted storage (KMS CMK). Automated backups: 7-day retention, daily snapshots. DB subnet group using database subnets (isolated from internet). Security group: allow only from ECS task security group on port 5432. Password: generated with random_password resource, stored in AWS Secrets Manager, injected into ECS task at runtime.

5
Multi-Environment Module Structure

Directory structure: modules/ (reusable: vpc, ecs, rds, alb), environments/dev/, environments/staging/, environments/prod/ — each environment calls modules with different variable values (instance sizes, replica counts, backup retention). Use Terraform workspaces or separate state files per environment. Environment-specific variables: dev uses smaller instances (cost), prod uses Multi-AZ (reliability). Backend configuration: each environment uses separate Terraform Cloud workspace or S3 state bucket prefix.

6
Security Scanning and Cost Optimization

tfsec: static analysis of Terraform files before apply — detect security misconfigurations (S3 bucket public access, security groups open to 0.0.0.0/0, unencrypted storage). Checkov: compliance scanning against CIS AWS Benchmark. Cost estimation: infracost CLI shows monthly cost of plan changes before applying — prevent accidental expensive resource creation. Tag enforcement: require tags (Environment, Team, CostCenter) via Sentinel policy or pre-commit validation. Drift detection: terraform plan run daily in CI/CD to detect out-of-band changes.

Code & Implementation

Core code for main.tf:

main.tf Terraform
# CATB.in Infrastructure — Terraform Configuration terraform {   required_version = ">= 1.6"   required_providers {     aws = { source = "hashicorp/aws", version = "~> 5.0" }   }   backend "s3" {     bucket = "catb-terraform-state"     key    = "prod/terraform.tfstate"     region = "ap-south-1"   } }  provider "aws" { region = "ap-south-1" }  module "vpc" {   source  = "terraform-aws-modules/vpc/aws"   version = "5.0"   name = "catb-prod-vpc"   cidr = "10.0.0.0/16"   azs             = ["ap-south-1a", "ap-south-1b"]   public_subnets  = ["10.0.1.0/24", "10.0.2.0/24"]   private_subnets = ["10.0.11.0/24", "10.0.12.0/24"]   enable_nat_gateway = true; single_nat_gateway = false  # HA NAT   tags = { Environment = "prod", Project = "catb" } }  resource "aws_ecs_cluster" "main" {   name = "catb-prod-cluster"   setting { name = "containerInsights", value = "enabled" } }  resource "aws_db_instance" "main" {   identifier        = "catb-prod-db"   engine            = "postgres"   engine_version    = "15.4"   instance_class    = "db.t3.medium"   allocated_storage = 100   storage_encrypted = true   multi_az          = true   backup_retention_period = 7   db_subnet_group_name    = aws_db_subnet_group.main.name   vpc_security_group_ids  = [aws_security_group.rds.id]   skip_final_snapshot     = false }

Testing & Troubleshooting

Test Cloud Infrastructure with Terraform by verifying each subsystem individually before full integration.

!
Troubleshooting Tips

Verify power voltages, check ground connections, use serial monitor for debug.

Real-World Applications

*Multi-cloud infrastructure automation
*Kubernetes cluster provisioning
*Development environment automation
*Disaster recovery infrastructure setup
*Database provisioning automation
*Network infrastructure management
*Security baseline automation
*Cost-optimized auto-scaling infrastructure

Extensions & Next Steps

  • Implement Terraform CDK (CDKTF) using Python instead of HCL
  • Build a policy-as-code framework using Sentinel
  • Create a custom Terraform provider for internal APIs
  • Implement Atlantis for automated plan/apply via PR comments
  • Build infrastructure testing with Terratest

Interactive Playground

Coming Soon

An interactive simulator will be available here — simulate circuits and run code in-browser without hardware.

Frequently Asked Questions

Why use Terraform instead of cloud provider CLI/console?
Terraform advantages: version control (infrastructure changes reviewed as code via PRs), reproducibility (apply same config to dev/staging/prod consistently), documentation (config is self-documenting vs undocumented console clicks), drift detection (terraform plan shows what changed outside Terraform), and rollback (git revert to previous state). Manual console/CLI: no audit trail (who changed what?), hard to reproduce, no testing before applying, and prone to human error at scale.
What is the difference between Terraform and Ansible?
Terraform: best for provisioning infrastructure (VMs, VPCs, databases, DNS records) — declarative, idempotent, state-aware. Creates and tracks cloud resources. Ansible: best for configuration management and application deployment (install packages, configure services, deploy code) — procedural (playbooks), agentless (SSH). Complementary: Terraform provisions the servers, Ansible configures what runs on them. HashiCorp Packer can also pre-bake AMIs with software installed, reducing Ansible's role.
Advertisement