Overview and What You Will Learn
This lab builds a complete AWS stack for a payment API service in Terraform: a network, an app server, object storage, and a database, all created from code in dependency order. Because everything is declared in files, the same configuration can be applied to a new environment or region by changing variable values.
You will build from the network layer up:
- A custom VPC with public and private subnets across two availability zones
- An Internet Gateway, a NAT Gateway, and route tables
- Security groups with least-privilege rules that reference each other
- An EC2 instance in a private subnet with an IAM role and IMDSv2 enforced
- An S3 bucket with versioning, encryption, lifecycle rules, and public access blocked
- An RDS PostgreSQL instance whose master password is generated and stored by AWS Secrets Manager
- Consistent tagging with provider
default_tagsand locals - Outputs for the values your application needs
SecurityThis lab creates billable resources, including a NAT Gateway and an RDS instance. Run
terraform destroywhen you finish the dev environment.
Why This Matters in Production
A hand-built environment drifts. Two engineers following the same wiki page end up with different security group rules and instance settings, and nobody can say exactly what is running. Teams at payment companies like Razorpay or Stripe keep infrastructure in Git so that an audit question such as "show me every resource and its configuration" is answered by the repository history, and a disaster recovery region can be created by running the same code with different variables. (The setup here is a teaching example, not any company's actual stack.)
Core Principles
The design puts anything that serves requests behind a boundary and keeps data stores private. Only the NAT Gateway sits in a public subnet, and the app server and database have no public IP.
Security groups reference each other instead of CIDR ranges: the database only accepts traffic from the app security group, and the app only accepts traffic from the load balancer security group.
Detailed Step-by-Step Practical Lab
How to Structure a Terraform Project for AWS
Splitting the configuration by concern keeps each file small and easy to review.
mkdir razorpay-payments-infra && cd razorpay-payments-infra touch versions.tf # Terraform and provider version constraintstouch provider.tf # AWS provider with default_tagstouch variables.tf # input variablestouch locals.tf # data lookups, naming, AZ selectiontouch vpc.tf # VPC, subnets, gateways, route tablestouch security.tf # security groupstouch compute.tf # IAM role and EC2 instancetouch storage.tf # S3 buckettouch database.tf # RDS subnet group, parameter group, instancetouch outputs.tf # values exposed after applytouch terraform.tfvarsHow to Pin Terraform and the AWS Provider
Pinning stops a newer provider release from changing behavior under you.
terraform { required_version = ">= 1.6.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } # Enable a remote backend before a team shares this stack # backend "s3" { # bucket = "razorpay-terraform-state" # key = "payments/prod/terraform.tfstate" # region = "ap-south-1" # use_lockfile = true # encrypt = true # }}# provider.tfprovider "aws" { region = var.aws_region # Applied to every taggable resource, so you do not repeat tags on each block default_tags { tags = { Project = var.project Environment = var.environment ManagedBy = "terraform" Repository = "github.com/razorpay-platform/payments-infra" CostCenter = "platform-${var.environment}" } }}How to Define Input Variables with Validation
Variables make one configuration reusable across environments, and validation rejects bad values before any API call.
# variables.tfvariable "aws_region" { description = "AWS region, ap-south-1 is Mumbai" type = string default = "ap-south-1"} variable "environment" { description = "Deployment environment, controls sizing and protection settings" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "Environment must be dev, staging, or prod." }} variable "project" { description = "Project prefix used in resource names and tags" type = string default = "razorpay-payments"} variable "vpc_cidr" { description = "CIDR block for the VPC, a /16 gives 65,536 addresses" type = string default = "10.0.0.0/16"} variable "public_subnet_cidrs" { description = "Public subnet CIDRs, one per AZ" type = list(string) default = ["10.0.1.0/24", "10.0.2.0/24"]} variable "private_subnet_cidrs" { description = "Private subnet CIDRs, one per AZ, for EC2 and RDS" type = list(string) default = ["10.0.11.0/24", "10.0.12.0/24"]} variable "ec2_instance_type" { description = "EC2 instance type for the application server" type = string default = "t3.medium"} variable "rds_instance_class" { description = "RDS instance class" type = string default = "db.t3.medium"} variable "rds_allocated_storage" { description = "RDS allocated storage in GB" type = number default = 20} variable "db_master_username" { description = "Master username for the RDS instance" type = string default = "payments_admin"} variable "enable_multi_az" { description = "Enable Multi-AZ for RDS, set true in prod" type = bool default = false}# terraform.tfvars (dev values, safe to commit because it holds no secrets)aws_region = "ap-south-1"environment = "dev"project = "razorpay-payments"ec2_instance_type = "t3.micro"rds_instance_class = "db.t3.micro"rds_allocated_storage = 20enable_multi_az = falseRememberThere is no database password variable. RDS generates the master password and stores it in Secrets Manager, so it never appears in your
.tfvarsfiles, shell history, or plan output.
How to Use Data Sources and Locals for Naming
Data sources look up the current account, region, AZs, and latest AMI so nothing is hardcoded.
# locals.tfdata "aws_availability_zones" "available" { state = "available" }data "aws_caller_identity" "current" {}data "aws_region" "current" {} data "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-2023.*-x86_64"] }} locals { name_prefix = "${var.project}-${var.environment}" # razorpay-payments-dev # First two AZs are enough for high availability here azs = slice(data.aws_availability_zones.available.names, 0, 2) # Bucket names are global, so add the account ID s3_data_bucket_name = "${local.name_prefix}-data-${data.aws_caller_identity.current.account_id}"}How to Create a VPC with Public and Private Subnets
A VPC needs subnets, an Internet Gateway for public traffic, and a NAT Gateway so private instances can reach the internet without being reachable from it.
# vpc.tfresource "aws_vpc" "main" { cidr_block = var.vpc_cidr enable_dns_support = true # needed to resolve the RDS endpoint enable_dns_hostnames = true tags = { Name = "${local.name_prefix}-vpc" }} resource "aws_subnet" "public" { count = length(var.public_subnet_cidrs) vpc_id = aws_vpc.main.id cidr_block = var.public_subnet_cidrs[count.index] availability_zone = local.azs[count.index] map_public_ip_on_launch = true tags = { Name = "${local.name_prefix}-public-${local.azs[count.index]}", Tier = "public" }} resource "aws_subnet" "private" { count = length(var.private_subnet_cidrs) vpc_id = aws_vpc.main.id cidr_block = var.private_subnet_cidrs[count.index] availability_zone = local.azs[count.index] tags = { Name = "${local.name_prefix}-private-${local.azs[count.index]}", Tier = "private" }} resource "aws_internet_gateway" "main" { vpc_id = aws_vpc.main.id tags = { Name = "${local.name_prefix}-igw" }} # The NAT Gateway needs a static public IPresource "aws_eip" "nat" { domain = "vpc" depends_on = [aws_internet_gateway.main] tags = { Name = "${local.name_prefix}-nat-eip" }} # Lives in a PUBLIC subnet, private route tables point at itresource "aws_nat_gateway" "main" { allocation_id = aws_eip.nat.id subnet_id = aws_subnet.public[0].id depends_on = [aws_internet_gateway.main] tags = { Name = "${local.name_prefix}-nat-gw" }} resource "aws_route_table" "public" { vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" gateway_id = aws_internet_gateway.main.id } tags = { Name = "${local.name_prefix}-public-rt" }} resource "aws_route_table_association" "public" { count = length(aws_subnet.public) subnet_id = aws_subnet.public[count.index].id route_table_id = aws_route_table.public.id} resource "aws_route_table" "private" { vpc_id = aws_vpc.main.id route { cidr_block = "0.0.0.0/0" nat_gateway_id = aws_nat_gateway.main.id # outbound only, through NAT } tags = { Name = "${local.name_prefix}-private-rt" }} resource "aws_route_table_association" "private" { count = length(aws_subnet.private) subnet_id = aws_subnet.private[count.index].id route_table_id = aws_route_table.private.id}How to Write Least-Privilege Security Groups
Referencing one security group from another keeps rules correct even when IP addresses change.
# security.tf # Load balancer SG (the ALB itself is out of scope for this lab)resource "aws_security_group" "alb" { name = "${local.name_prefix}-alb-sg" description = "ALB: HTTPS and HTTP from the internet" vpc_id = aws_vpc.main.id ingress { description = "HTTPS from internet" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { description = "HTTP for redirect to HTTPS" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { description = "To app servers inside the VPC" from_port = 8080 to_port = 8080 protocol = "tcp" cidr_blocks = [var.vpc_cidr] } tags = { Name = "${local.name_prefix}-alb-sg" }} resource "aws_security_group" "app" { name = "${local.name_prefix}-app-sg" description = "App server: inbound from ALB only" vpc_id = aws_vpc.main.id ingress { description = "App traffic from the ALB security group" from_port = 8080 to_port = 8080 protocol = "tcp" security_groups = [aws_security_group.alb.id] } egress { description = "Outbound to RDS, AWS APIs, and package mirrors" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } tags = { Name = "${local.name_prefix}-app-sg" }} resource "aws_security_group" "rds" { name = "${local.name_prefix}-rds-sg" description = "RDS: PostgreSQL from app servers only" vpc_id = aws_vpc.main.id ingress { description = "PostgreSQL from the app security group" from_port = 5432 to_port = 5432 protocol = "tcp" security_groups = [aws_security_group.app.id] } tags = { Name = "${local.name_prefix}-rds-sg" }}How to Attach an IAM Role to an EC2 Instance
An instance profile lets the app call AWS APIs with temporary credentials, so no access keys are stored on the server.
# compute.tf (IAM section)data "aws_iam_policy_document" "ec2_assume_role" { statement { effect = "Allow" actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["ec2.amazonaws.com"] } }} resource "aws_iam_role" "app" { name = "${local.name_prefix}-ec2-role" assume_role_policy = data.aws_iam_policy_document.ec2_assume_role.json} data "aws_iam_policy_document" "app_permissions" { statement { sid = "S3DataBucket" effect = "Allow" actions = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket"] resources = [aws_s3_bucket.app_data.arn, "${aws_s3_bucket.app_data.arn}/*"] } # Read only the secret RDS created for the master password statement { sid = "ReadDatabaseSecret" effect = "Allow" actions = ["secretsmanager:GetSecretValue"] resources = [aws_db_instance.main.master_user_secret[0].secret_arn] } statement { sid = "CloudWatchLogs" effect = "Allow" actions = ["logs:CreateLogStream", "logs:PutLogEvents"] resources = ["arn:aws:logs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:log-group:/${var.project}/*:*"] }} resource "aws_iam_role_policy" "app" { name = "${local.name_prefix}-app-policy" role = aws_iam_role.app.id policy = data.aws_iam_policy_document.app_permissions.json} # Session Manager access, so no bastion host or SSH key is neededresource "aws_iam_role_policy_attachment" "ssm" { role = aws_iam_role.app.name policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"} resource "aws_iam_instance_profile" "app" { name = "${local.name_prefix}-ec2-profile" role = aws_iam_role.app.name}How to Launch a Hardened EC2 Instance in a Private Subnet
Enforcing IMDSv2 and an encrypted root volume are the two settings most often missed on EC2.
# compute.tf (EC2 section)resource "aws_instance" "app" { ami = data.aws_ami.amazon_linux.id instance_type = var.ec2_instance_type subnet_id = aws_subnet.private[0].id vpc_security_group_ids = [aws_security_group.app.id] iam_instance_profile = aws_iam_instance_profile.app.name # Runs once on first boot user_data = <<-EOF #!/bin/bash set -euo pipefail dnf update -y dnf install -y amazon-cloudwatch-agent mkdir -p /opt/app echo "ENVIRONMENT=${var.environment}" > /opt/app/config.env echo "PROJECT=${var.project}" >> /opt/app/config.env # Replace with your real deployment steps EOF # IMDSv2 only: blocks SSRF-based theft of instance credentials metadata_options { http_endpoint = "enabled" http_tokens = "required" http_put_response_hop_limit = 1 } root_block_device { volume_type = "gp3" volume_size = 30 encrypted = true delete_on_termination = true } tags = { Name = "${local.name_prefix}-app-server" }}How to Create a Secure S3 Bucket with Terraform
Since provider v4, each S3 setting is its own resource. Block public access first, then add versioning, encryption, and lifecycle rules.
# storage.tfresource "aws_s3_bucket" "app_data" { bucket = local.s3_data_bucket_name tags = { Name = "${local.name_prefix}-data" }} resource "aws_s3_bucket_public_access_block" "app_data" { bucket = aws_s3_bucket.app_data.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true} resource "aws_s3_bucket_versioning" "app_data" { bucket = aws_s3_bucket.app_data.id versioning_configuration { status = "Enabled" # lets you recover deleted or overwritten objects }} resource "aws_s3_bucket_server_side_encryption_configuration" "app_data" { bucket = aws_s3_bucket.app_data.id rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } }} resource "aws_s3_bucket_lifecycle_configuration" "app_data" { bucket = aws_s3_bucket.app_data.id depends_on = [aws_s3_bucket_versioning.app_data] rule { id = "tiering-and-expiry" status = "Enabled" filter {} # apply to every object transition { days = 30 storage_class = "STANDARD_IA" } transition { days = 90 storage_class = "GLACIER" } expiration { days = 365 # adjust to your retention policy } # With versioning on, old versions need their own expiry noncurrent_version_expiration { noncurrent_days = 90 } }}How to Provision an RDS PostgreSQL Instance with Terraform
Setting manage_master_user_password = true makes RDS create the password and store it in Secrets Manager, which keeps it out of your configuration and state.
# database.tfresource "aws_db_subnet_group" "main" { name = "${local.name_prefix}-db-subnet-group" description = "Private subnets for ${local.name_prefix} PostgreSQL" subnet_ids = aws_subnet.private[*].id tags = { Name = "${local.name_prefix}-db-subnet-group" }} resource "aws_db_parameter_group" "postgres" { name = "${local.name_prefix}-pg16" family = "postgres16" description = "PostgreSQL 16 parameters for ${local.name_prefix}" parameter { name = "log_statement" value = "ddl" # log CREATE, ALTER, DROP } parameter { name = "log_min_duration_statement" value = "1000" # log queries slower than one second } tags = { Name = "${local.name_prefix}-pg16-params" }} resource "aws_db_instance" "main" { identifier = "${local.name_prefix}-postgres" engine = "postgres" engine_version = "16" # major only, RDS picks the default minor parameter_group_name = aws_db_parameter_group.postgres.name instance_class = var.rds_instance_class allocated_storage = var.rds_allocated_storage max_allocated_storage = var.rds_allocated_storage * 3 # storage autoscaling storage_type = "gp3" storage_encrypted = true db_name = "payments" username = var.db_master_username # RDS generates the password and keeps it in Secrets Manager manage_master_user_password = true db_subnet_group_name = aws_db_subnet_group.main.name vpc_security_group_ids = [aws_security_group.rds.id] publicly_accessible = false multi_az = var.enable_multi_az backup_retention_period = var.environment == "prod" ? 30 : 3 backup_window = "03:00-04:00" # UTC maintenance_window = "sun:04:00-sun:05:00" # UTC deletion_protection = var.environment == "prod" skip_final_snapshot = var.environment != "prod" final_snapshot_identifier = "${local.name_prefix}-final-snapshot" # Not supported on the smallest burstable classes, so enable it in prod only performance_insights_enabled = var.environment == "prod" tags = { Name = "${local.name_prefix}-postgres" }}How to Expose Terraform Outputs for Your Application
Outputs publish the identifiers other tools and configurations need.
# outputs.tfoutput "vpc_id" { description = "VPC ID, usable from other configurations through remote state" value = aws_vpc.main.id} output "private_subnet_ids" { description = "Private subnet IDs for EC2 and RDS" value = aws_subnet.private[*].id} output "instance_id" { description = "EC2 instance ID of the application server" value = aws_instance.app.id} output "s3_bucket_name" { description = "Set as APP_DATA_BUCKET in your application" value = aws_s3_bucket.app_data.id} output "rds_endpoint" { description = "Set as DB_HOST in your application" value = aws_db_instance.main.address} output "rds_master_secret_arn" { description = "Secrets Manager ARN holding the generated DB credentials" value = aws_db_instance.main.master_user_secret[0].secret_arn}How to Plan and Apply the Full Stack
Always validate and review the plan before applying. A plan file guarantees you apply exactly what you reviewed.
terraform initterraform validateterraform plan -out=tfplan.binaryterraform apply tfplan.binary# Abridged, illustrative outputaws_vpc.main: Creation complete after 3s [id=vpc-0a1b2c3d]aws_db_instance.main: Still creating... [4m0s elapsed]aws_db_instance.main: Creation complete after 5m12s Apply complete! Resources: 30 added, 0 changed, 0 destroyed. Outputs:rds_endpoint = "razorpay-payments-dev-postgres.abc123.ap-south-1.rds.amazonaws.com"s3_bucket_name = "razorpay-payments-dev-data-123456789012"Retrieve the generated database credentials when you need them:
aws secretsmanager get-secret-value \ --secret-id "$(terraform output -raw rds_master_secret_arn)" \ --query SecretString --output textHow to Apply the Same Stack for Production
The configuration stays identical, only the values change.
cat > prod.tfvars << 'EOF'environment = "prod"ec2_instance_type = "t3.large"rds_instance_class = "db.r6g.large"rds_allocated_storage = 500enable_multi_az = trueEOF terraform plan -var-file=prod.tfvars -out=tfplan.binaryterraform apply tfplan.binaryTipUse a separate state key or workspace per environment so a dev apply can never touch production resources.
Production Best Practices & Common Pitfalls
- Keep database passwords out of Terraform inputs. Use
manage_master_user_password = trueor read from Secrets Manager. Anything passed as a variable ends up in state. - Enable
deletion_protectionand a final snapshot in production. A mistakenterraform destroythen fails instead of deleting the database. - Enforce IMDSv2 with
http_tokens = "required". This blocks SSRF attacks from reading the instance's IAM credentials. - Encrypt volumes explicitly.
encrypted = trueon EC2 root volumes andstorage_encrypted = trueon RDS are not guaranteed defaults. - Use
gp3for new volumes. It is cheaper thangp2and lets you set IOPS and throughput independently. - Use one NAT Gateway per AZ in production. This lab uses one to save cost, which means an AZ failure removes outbound internet for private subnets in the other AZ.
- Store state remotely with locking and encryption. A local state file cannot be shared safely and may contain sensitive attributes.
Common MistakeRunning the dev configuration with
terraform apply -auto-approveand forgetting to destroy it. The NAT Gateway and RDS instance bill by the hour.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
terraform plan -target=aws_vpc.main |
Plan a single resource |
terraform apply -var-file=prod.tfvars |
Apply with production values |
terraform state list |
List every managed resource |
terraform state show aws_db_instance.main |
Show all RDS attributes |
terraform output rds_endpoint |
Read an output after apply |
terraform destroy -target=aws_instance.app |
Destroy only the EC2 instance |
| Error | Root Cause | Fix |
|---|---|---|
DBSubnetGroupDoesNotCoverEnoughAZs |
RDS subnet group has subnets in fewer than two AZs | Add private subnets from at least two AZs |
BucketAlreadyExists |
Bucket name is taken by another AWS account | Keep the account ID suffix in the name |
AddressLimitExceeded |
Elastic IP quota reached | Release unused EIPs or request a quota increase |
InvalidParameterCombination on Performance Insights |
Instance class does not support it | Disable it for small classes such as db.t3.micro |
| RDS apply takes 5 minutes or more | Normal RDS provisioning time | Wait, other independent resources continue in parallel |