Skip to main content

Database

In our Lego city analogy, the database is the library or vault where all records are safely stored. Without it, the city has no memory. In Terraform, this means configuring Amazon RDS (Relational Database Service) to provide secure, scalable, and highly available storage for the application tier. This chapter ensures our data layer is resilient, protected, and properly connected to the app tier.


Key Concepts

1. Amazon RDS Overview

  • Managed relational database service (MySQL, PostgreSQL, etc.).
  • Handles backups, patching, and scaling automatically.
  • Supports multi‑AZ deployments for high availability.

2. Database Deployment with Terraform

resource "aws_db_instance" "app_db" {
  identifier        = "app-database"
  engine            = "mysql"
  instance_class    = "db.t3.micro"
  allocated_storage = 20
  username          = var.db_username
  password          = var.db_password
  db_subnet_group_name = aws_db_subnet_group.app_db_subnet.id
  vpc_security_group_ids = [aws_security_group.db_sg.id]
  skip_final_snapshot = true
}

3. Subnet Groups

  • RDS requires DB subnet groups (private subnets).
resource "aws_db_subnet_group" "app_db_subnet" {
  name       = "app-db-subnet"
  subnet_ids = [aws_subnet.private1.id, aws_subnet.private2.id]
}

4. Security Groups

  • DB SG allows traffic only from App SG.
resource "aws_security_group" "db_sg" {
  vpc_id = aws_vpc.main.id

  ingress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "tcp"
    security_groups = [aws_security_group.app_sg.id]
  }
}

5. Parameters & Backups

  • Configure automated backups.
  • Enable multi‑AZ for high availability.
  • Use parameter groups for tuning DB settings.

Hands‑On Lab / Demo

Lab: Deploying RDS with Terraform

  1. Create DB subnet group in private subnets.
  2. Create DB security group allowing traffic only from App SG.
  3. Deploy RDS instance with MySQL engine.
  4. Verify connectivity from App tier EC2 instances.
  5. Test backup and restore functionality.

Pro Tips & Best Practices

  • Always place DB in private subnets.
  • Use Terraform variables for credentials (never hardcode).
  • Enable multi‑AZ for production workloads.
  • Configure automated backups for disaster recovery.
  • Use parameter groups for performance tuning.

Summary & Cheatsheet

  • RDS = Managed relational database.
  • Subnet groups = Private placement.
  • Security groups = Controlled access.
  • Parameters & backups = Reliability and resilience.
Quick mnemonic: DB = Secure, Private, Backed‑Up

The Hackers Notebook

The database is the memory of your 3‑tier infrastructure. By deploying RDS in private subnets with backups and multi‑AZ, you ensure secure and reliable data storage.


Tips, Tricks, Roadmaps, Resources, Networking, Motivation, Guidance, and Cool Stuff ♥

Updated on Dec 31, 2025