π 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