๐ Terraform Day 22: Secure Two-Tier Architecture on AWS (EC2 + RDS)
Source: Dev.to

๐งฑ Architecture Overview
The deployed architecture consists of:
๐ Web Tier
- EC2 instance in a public subnet
- Accessible via public DNS
- Runs a Flask application
- Uses Security Groups to restrict inbound access
๐๏ธ Database Tier
- MySQL RDS instance
- Hosted in private subnets
- No direct internet access
- Accepts traffic only from web tier security group
๐ Secrets Management
- Database username & password generated dynamically
- Stored securely in AWS Secrets Manager
- Retrieved by EC2 during boot via user data
๐งฉ Terraform Module Design
This project is built using custom Terraform modules, a critical realโworld practice.
Modules used:
- VPC module โ VPC, public & private subnets, Internet Gateway, NAT Gateway, route tables
- Security Group module โ Web SG (HTTP access), DB SG (MySQL access only from web SG)
- Secrets module โ Random password generation, Secrets Manager storage
- RDS module โ MySQL instance, private subnet placement, credentials injected from Secrets Manager
The root module orchestrates everything by passing outputs between modules.
๐ Secure Credential Handling (Critical)
One of the most important lessons in Dayโฏ22:
-
โ No credentials in Terraform code
-
โ No credentials in
variables.tf -
โ No credentials in userโdata scripts
-
โ Password generated using
random_password -
โ Stored in AWS Secrets Manager
-
โ Retrieved securely at runtime
This is mandatory in real production environments.
โ๏ธ Application Deployment with User Data
The EC2 instance uses user data to:
- Install system dependencies
- Install Python and Flask
- Fetch database credentials from Secrets Manager
- Configure environment variables
- Start the Flask application automatically
Result: Infrastructure and application deploy together โ fully automated.
๐ Terraform Workflow Used
Standard, productionโsafe workflow:
terraform init
terraform plan
terraform apply
Notes:
- RDS provisioning takes time โ expected behavior
- Outputs expose the application endpoint safely
- Infrastructure must be destroyed after testing to avoid costs