๐Ÿš€ Terraform Day 22: Secure Two-Tier Architecture on AWS (EC2 + RDS)

Published: (December 28, 2025 at 06:39 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for ๐Ÿš€ Terraform Day 22: Secure Two-Tier Architecture on AWS (EC2 + RDS)

๐Ÿงฑ 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
Back to Blog

Related posts

Read more ยป