πŸš€ 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 Β»

Launch an AWS EC2 Instance

Introduction This guide walks you through launching an AWS EC2 instance, installing Docker, and running NGINX inside a Docker container. By the end you will ha...

AWS VPC

What is AWS VPC? An AWS Virtual Private Cloud VPC is a logically isolated network inside AWS where you can launch resources such as: - EC2 instances - Database...