πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

We should learn about RDS to efficiently manage, automate, and scale production-grade relational databases without handling the underlying infrastructure.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


Learning points:

πŸ’‘ What is Amazon RDS, and why it’s used in cloud-native DevOps environments
πŸ’‘ Supported database engines: MySQL, PostgreSQL, MariaDB, SQL Server, Oracle, Aurora
πŸ’‘ Understanding RDS components: DB instance, subnet groups, parameter groups, option groups
πŸ’‘ RDS deployment types: Single-AZ vs Multi-AZ
πŸ’‘ Security best practices: VPC, subnet isolation, security groups, and IAM integration
πŸ’‘ Automatic backups, snapshots, and Point-in-Time Recovery
πŸ’‘ Monitoring and scaling RDS

🧠 Learn here:

Official AWS Video on RDS

πŸ‘‰ More RDS Learning Videos

AWS RDS Architecture

Amazon RDS - Relational Database Service

Amazon RDS (Relational Database Service) is a managed service provided by AWS that makes it easy to set up, operate, and scale a relational database in the cloud.

Key Features

  • Fully Managed: AWS handles backups, patching, monitoring, and maintenance.
  • Supports Multiple Engines:
    • Amazon Aurora (MySQL/PostgreSQL-compatible)
    • MySQL
    • PostgreSQL
    • MariaDB
    • Oracle
    • SQL Server
  • Scalability: Easily scale compute and storage independently.
  • High Availability: Multi-AZ deployments for automatic failover.
  • Automated Backups: Point-in-time recovery.
  • Security: Encryption at rest and in transit, IAM integration, VPC support.

πŸ’‘ Why It’s Used in Cloud-Native DevOps

Amazon RDS is popular in DevOps environments due to its support for automation, scalability, high availability, and integration with AWS tools.

1. Automation-Friendly

  • Supports Infrastructure as Code (Terraform, CloudFormation, AWS CDK).
  • Integrates with CI/CD pipelines.

2. Managed Operations

  • AWS handles patching, backups, and updates.
  • Reduces operational overhead and human error.

3. On-Demand Scalability

  • Auto-scaling storage.
  • Scale read replicas easily.

4. High Availability & DR

  • Multi-AZ deployments.
  • Point-in-time recovery.
  • Cross-region read replicas.

5. Security and Compliance

  • VPC, IAM, KMS, CloudTrail integration.
  • Encryption and compliance support (HIPAA, SOC 2).

6. Observability and Monitoring

  • CloudWatch, Enhanced Monitoring, CloudWatch Database Insights (formerly Performance Insights).

🧠 Supported Database Engines

Engine Description
MySQL Popular open-source database for web apps.
PostgreSQL Advanced open-source DB, great for complex queries.
MariaDB MySQL fork with enhancements.
SQL Server Microsoft’s enterprise-grade DB.
Oracle Commercial DB for enterprise use.
Db2 IBM’s enterprise database (on RDS since 2023).
Aurora AWS-built engine compatible with MySQL and PostgreSQL; AWS quotes up to 5x the throughput of standard MySQL and 3x of PostgreSQL.

🧩 RDS Components

1. DB Instance

  • Virtual DB environment (compute, storage, network)
  • Example: db.t3.medium, 100 GB PostgreSQL

2. DB Subnet Group

  • Group of subnets across AZs.
  • Required for RDS in VPC.

3. DB Parameter Group

  • Configuration set for DB engine.
  • Customizes buffer sizes, logging, etc.

4. DB Option Group

  • Add advanced engine-specific features.
  • E.g., Oracle Data Guard, SQL Server SQL Agent.

βš™οΈ RDS Deployment Types

Single-AZ Deployment

  • Runs in one AZ.
  • Use Cases: Dev/Test, cost-sensitive apps.

Multi-AZ Deployment

  • Synchronous replication to standby in another AZ.
  • Use Cases: Production, critical systems.
Feature Single-AZ Multi-AZ
Availability Low High (Auto Failover)
Cost Lower Higher
Replication None Synchronous
Failover Manual Automatic
Backups On primary On standby
Best For Dev/Test Production

πŸ” Security Best Practices

1. VPC

  • Use private subnets.
  • Avoid public access.

2. Subnet Isolation

  • Separate app and DB tiers.

3. Security Groups

  • Firewall rules for RDS.
  • Allow only trusted IPs and required ports.

4. IAM Integration

  • Avoid hardcoded credentials.
  • Use IAM roles or Secrets Manager.

βœ… Tips

  • Enable encryption (KMS + SSL/TLS).
  • Monitor failed logins.
  • Use CloudTrail for auditing.

πŸ’Ύ Backup & Recovery

1. Automatic Backups

  • Entire DB instance backed up.
  • Point-in-Time Recovery.
  • Configurable retention (1-35 days).

2. Manual Snapshots

  • User-initiated backups.
  • Ideal before updates/migrations.

3. Point-in-Time Recovery (PITR)

  • Restore to any second in backup window.
  • Critical for data recovery scenarios.

πŸ“ˆ Monitoring RDS

CloudWatch Metrics

Metric Description
CPUUtilization CPU usage %
FreeableMemory Available memory
FreeStorageSpace Remaining disk space
ReadIOPS / WriteIOPS Disk I/O operations per second
DatabaseConnections Number of active DB connections
ReplicaLag Lag in seconds for read replicas

Enhanced Monitoring

  • OS-level metrics every 1–60 seconds.
  • Deeper insights than CloudWatch.

Database Insights (formerly Performance Insights)

  • Visualize DB load, slow queries and wait events. Since July 31, 2026 the Performance Insights console redirects to CloudWatch Database Insights (Standard mode is the free default; Advanced adds execution plans and fleet views).
  • Supported: PostgreSQL, MySQL, Aurora, etc.

πŸ“Š Scaling RDS

1. Vertical Scaling

  • Upgrade instance type (e.g., db.t3.medium β†’ db.m5.large).
  • Causes a short outage while the instance is replaced; with Multi-AZ, RDS resizes the standby first and fails over, so downtime is about a minute.

2. Storage Scaling

  • RDS storage autoscaling (set a maximum) works for every engine; Aurora storage grows automatically.
  • You can also resize manually, but storage can only grow, never shrink.

3. Read Replicas

  • Offload read traffic.
  • MySQL, PostgreSQL, MariaDB, Oracle, SQL Server and Aurora.
  • Can be promoted to standalone DB.

βœ… Best Practices Summary

  • Use Multi-AZ for production.
  • Automate via Terraform/CloudFormation.
  • Monitor via CloudWatch & Database Insights.
  • Use IAM roles, Secrets Manager, and private VPC subnets.
  • Enable encryption and PITR.
  • Test restore and scaling regularly.

🧠 Tip: Combine RDS with other AWS services like Lambda, ECS, or EKS for modern cloud-native app stacks.

πŸ“šοΈ Additional Resources:

πŸ“Œ What is Amazon RDS? – AWS Docs
πŸ“Œ Amazon RDS Pricing
πŸ“Œ Launch RDS using AWS Console
πŸ“Œ Connect to RDS from EC2
πŸ“Œ Backup & Restore in RDS
πŸ“Œ CloudWatch for RDS Monitoring


πŸ”₯ Challenges

πŸ”Ή Challenge 1: Create a MySQL or PostgreSQL RDS instance using the AWS Console
πŸ”Ή Challenge 2: Connect to the RDS instance using DBeaver, MySQL CLI, or psql (based on what DB you have selected)
πŸ”Ή Challenge 3: Create a sample table, insert some records, and query them
πŸ”Ή Challenge 4: Enable automated backups and take a manual snapshot
πŸ”Ή Challenge 5: Create a read-only IAM user with access to RDS monitoring only



πŸ”Ή Challenge 6: Launch RDS in a private subnet and connect using a Bastion Host
πŸ”Ή Challenge 7: Configure an RDS parameter group to change a DB setting (e.g., max_connections)
πŸ”Ή Challenge 8: Set up CloudWatch Alarms for high CPU or storage usage
πŸ”Ή Challenge 9: Use RDS Snapshot Restore to clone your DB into a new instance
πŸ”Ή Challenge 10: Use AWS CLI to automate RDS snapshot creation



Scenario-based:
πŸ”Ή Challenge 11: Host a Python app in EC2 with DB (MySQL) in RDS

πŸ’‘ Step 1: Deploy a simple Flask or Node.js app on EC2
πŸ’‘ Step 2: Store app data (users, posts, etc.) in your Amazon RDS database
πŸ’‘ Step 3: Configure CloudWatch Alarms for database health
πŸ’‘ Step 4: Schedule a snapshot and demonstrate recovery
πŸ’‘ Step 5: Document and push your setup to GitHub



βœ… Solutions

πŸ”Ή Challenge 1: Create a MySQL or PostgreSQL RDS Instance Using the AWS Console

Step 1: Go to the RDS Console

Step 2: Click on β€œCreate Database”

  • Choose a database creation method:
    • βœ… Select Standard create

Step 3: Engine Options

  • Engine type: Choose MySQL or PostgreSQL
  • Version: Select a supported major version (e.g., MySQL 8.4 or PostgreSQL 17); RDS MySQL 8.0 left standard support on July 31, 2026

Step 4: Templates

  • Choose:
    • βœ… Free tier (if eligible) OR
    • Production / Dev/Test

Step 5: Settings

  • DB instance identifier: my-rds-instance
  • Master username: admin
  • Password: Create & confirm a strong password

Step 6: Instance Configuration

  • DB instance class:
    • Free tier: db.t3.micro
    • Production: Choose based on CPU/RAM requirements
  • Storage:
    • Type: General Purpose (SSD)
    • Allocated storage: e.g., 20 GB
    • βœ… Enable autoscaling if needed

Step 7: Connectivity

  • VPC: Choose your default/custom VPC
  • Subnet group: Choose default (or custom)
  • Public access:
    • βœ… Yes β†’ if you want to connect from your laptop
    • ❌ No β†’ for internal-only access (e.g., from EC2)
  • VPC security group:
    • Choose existing or create new
    • Ensure port 3306 (MySQL) or 5432 (PostgreSQL) is open to your IP or app server

Step 8: Database Authentication

  • Keep default as Password authentication
  • (Optionally add IAM authentication later)

Step 9: Additional Config (Optional)

  • Enable automated backups
  • Enable Database Insights
  • Enable deletion protection (for production environments)

Step 10: Click β€œCreate Database”

  • It will take 5–10 mins to provision the database

Step 11: Connect to the RDS Instance

  • Once status is Available:
    • Endpoint: Copy the DB endpoint
    • Port: 3306 (MySQL) or 5432 (PostgreSQL)
    • Use a CLI or tool like mysql, psql, DBeaver, or MySQL Workbench to connect



βœ… Challenge 2: Connect to the RDS instance using DBeaver, MySQL CLI, or psql

πŸ”Έ MySQL:

mysql -h <endpoint> -P 3306 -u admin -p

πŸ”Έ PostgreSQL:

psql -h <endpoint> -p 5432 -U admin -d postgres

βœ… Challenge 3: Create a sample table, insert some records, and query them

If you have selected MySQL:

πŸ”Έ Method: MySQL CLI

Step 1: Connect to the DB

mysql -h <RDS-ENDPOINT> -P 3306 -u admin -p

Enter the password when prompted.

Step 2: Create a Database

CREATE DATABASE testdb;
USE testdb;

Step 3: Create Table

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

Step 4: Insert Sample Records

INSERT INTO users (name, email)
VALUES
  ('Alice', '[email protected]'),
  ('Bob', '[email protected]'),
  ('Charlie', '[email protected]');

Step 5: Query the Data

SELECT * FROM users;

Output:

+----+---------+---------------------+
| id | name    | email               |
+----+---------+---------------------+
|  1 | Alice   | [email protected]   |
|  2 | Bob     | [email protected]     |
|  3 | Charlie | [email protected] |
+----+---------+---------------------+

If you have selected PostgreSQL:

πŸ”Έ Method: psql CLI

Step 1: Connect to the DB

psql -h <RDS-ENDPOINT> -U admin -d postgres -p 5432

Enter the password when prompted.

Step 2: Create a Database (Optional)

CREATE DATABASE testdb;
\c testdb

Step 3: Create Table

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

Step 4: Insert Sample Records

INSERT INTO users (name, email)
VALUES
  ('Alice', '[email protected]'),
  ('Bob', '[email protected]'),
  ('Charlie', '[email protected]');

Step 5: Query the Table

SELECT * FROM users;


Challenge 4: Enable Automated Backups and Take a Manual Snapshot

Step 1: Enable Automated Backups

  1. Go to RDS Console β†’ Databases
  2. Select your RDS instance
  3. Click Modify
  4. Scroll to Backup section:
    • Enable automated backups: βœ… Yes
    • Backup retention period: e.g., 7 days
    • Preferred backup window: (optional) choose a low-traffic time
  5. Click Continue β†’ Apply Immediately

βœ… RDS will now create daily backups automatically.

Step 2: Create a Manual Snapshot

  1. Go to RDS Console β†’ Databases
  2. Select your DB instance β†’ Actions β†’ Take snapshot
  3. Enter a Snapshot name: e.g., manual-snapshot-preupgrade
  4. Click Take Snapshot
  5. ⏳ Wait for the snapshot status to become available

Step 3: View Snapshots

  • Go to Snapshots β†’ Manual (for user-created)
  • Go to Snapshots β†’ Automated (for AWS-managed backups)

You can:

  • Restore to a new instance
  • Share snapshot with another AWS account
  • Export snapshot to S3 (Aurora & supported engines)

Challenge 5: Create a Read-Only IAM User with Access to RDS Monitoring Only

Using AWS Console

Step 1: Create IAM User

  1. Go to IAM Console β†’ Users β†’ Add users
  2. User name: rds-monitor-user
  3. Access type:
    • βœ… Console access (for dashboard view) OR
    • βœ… Programmatic access (CLI/SDKs)
  4. Set password or generate access keys
  5. Click Next: Permissions

Step 2: Attach Permissions

  1. Click Create policy β†’ Go to JSON tab
  2. Paste the following JSON:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "rds:Describe*",
        "cloudwatch:GetMetricData",
        "cloudwatch:GetMetricStatistics",
        "cloudwatch:ListMetrics"
      ],
      "Resource": "*"
    }
  ]
}
  1. Name the policy: RDSMonitoringReadOnly
  2. Create and attach this policy to rds-monitor-user

Step 3: Finish & Verify Access

  • You’ll receive the login URL and credentials
  • Login via AWS Console and verify:
    • βœ… Can view RDS instances
    • βœ… Can see metrics in CloudWatch
    • ❌ Cannot delete/modify anything

Using AWS CLI

Step 1: Create IAM User

aws iam create-user --user-name rds-monitor-user

Step 2: Create Custom Policy

  1. Create a file rds-monitor-policy.json:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "rds:Describe*",
        "cloudwatch:GetMetricData",
        "cloudwatch:GetMetricStatistics",
        "cloudwatch:ListMetrics"
      ],
      "Resource": "*"
    }
  ]
}
  1. Create the policy:
aws iam create-policy \
  --policy-name RDSMonitoringReadOnly \
  --policy-document file://rds-monitor-policy.json

Step 3: Attach Policy to User

aws iam attach-user-policy \
  --user-name rds-monitor-user \
  --policy-arn arn:aws:iam::<your-account-id>:policy/RDSMonitoringReadOnly

βœ… Your IAM user now has read-only access to RDS and related CloudWatch metrics.


βœ… Challenge 6: Launch RDS in a Private Subnet and Connect Using a Bastion Host

Step 1: Set Up the VPC & Subnets (If Not Already Done)

Subnet Type Contains Public IP
Public Subnet Bastion EC2 Yes
Private Subnet RDS Instance No

Ensure:

  • NAT Gateway exists for private subnet (for RDS upgrades/patches).
  • Internet Gateway exists and routes from public subnet.

Step 2: Launch RDS in Private Subnet

  • Go to RDS Console β†’ Create database
  • Choose engine: βœ… MySQL / PostgreSQL
  • Select Standard create
  • Select VPC and choose subnet group with private subnets
  • Public access: ❌ No
  • VPC security group:
    • Create or use one that allows port 3306 (MySQL) or 5432 (PostgreSQL) from Bastion EC2's SG
  • Complete DB creation
  • βœ… Your RDS now only has a private IP

Step 3: Launch Bastion EC2 in Public Subnet

  • Launch EC2 instance in the public subnet of the same VPC
  • Select Amazon Linux / Ubuntu
  • Enable Auto-assign public IP: βœ… Yes
  • Attach a security group that:
    • Allows SSH from your IP (port 22)
    • Allows egress to private subnet
  • Save key pair (e.g., bastion.pem)

Step 4: Security Group Setup

Security Group Inbound Rules
Bastion SG SSH (22) from your IP
RDS SG DB port (3306/5432) from Bastion SG only

Step 5: Connect from Local Machine to RDS via Bastion

Option 1: SSH into Bastion, then connect to DB

ssh -i bastion.pem ec2-user@<Bastion-Public-IP>
# Then connect to RDS:
# MySQL
mysql -h <RDS-private-endpoint> -u admin -p
# PostgreSQL
psql -h <RDS-private-endpoint> -U admin -d postgres

Option 2: Use SSH Tunnel from Local Machine

ssh -i bastion.pem -L 3307:<RDS-Private-Endpoint>:3306 ec2-user@<Bastion-Public-IP>
# Then connect locally
mysql -h 127.0.0.1 -P 3307 -u admin -p

βœ… Challenge 7: Configure RDS Parameter Group to Change a DB Setting (e.g., max_connections)

Step 1: Create a Custom Parameter Group

  • Go to RDS Console β†’ Parameter groups
  • Click Create parameter group
  • Parameter group family: e.g., mysql8.4, postgres17
  • Type: DB Parameter Group
  • Name: custom-mysql-pg
  • Description: Increase max_connections
  • Click Create

Step 2: Modify the Parameter

  • Click on the new parameter group
  • Search for max_connections
  • Change value to (e.g., 500)
  • Click Save changes

Step 3: Apply Parameter Group to RDS

  • Go to RDS β†’ Databases
  • Select DB instance β†’ Modify
  • Under DB parameter group, choose custom-mysql-pg
  • Click Continue β†’ Apply Immediately
⚠️ Attaching a new parameter group always needs a reboot. After that, dynamic parameters (MySQL max_connections) apply immediately, while static ones (PostgreSQL max_connections) still need a reboot.

Step 4: Reboot the Instance

  • Go to RDS instance β†’ Actions β†’ Reboot

Step 5: Verify the Change

MySQL:

SHOW VARIABLES LIKE 'max_connections';

PostgreSQL:

SHOW max_connections;

βš–οΈ AWS CLI Commands

Step 1: Create Parameter Group

aws rds create-db-parameter-group \
  --db-parameter-group-name custom-mysql-pg \
  --db-parameter-group-family mysql8.4 \
  --description "Custom parameter group with higher max_connections"

Step 2: Modify Parameter

aws rds modify-db-parameter-group \
  --db-parameter-group-name custom-mysql-pg \
  --parameters "ParameterName=max_connections,ParameterValue=500,ApplyMethod=immediate"

Step 3: Attach to RDS Instance

aws rds modify-db-instance \
  --db-instance-identifier my-rds-instance \
  --db-parameter-group-name custom-mysql-pg \
  --apply-immediately

Step 4: Reboot (If Required)

aws rds reboot-db-instance \
  --db-instance-identifier my-rds-instance

The rest of the steps are the same.



πŸ”Ή Challenge 8: Set up CloudWatch Alarms for High CPU or Storage Usage

βœ… Using AWS Console

Step 1: Go to CloudWatch β†’ Alarms β†’ Create Alarm

Step 2: Select Metric

  • Browse: RDS β†’ Per-Database Metrics β†’ [DBInstanceIdentifier]
  • Choose:
    • CPUUtilization or
    • FreeStorageSpace

Step 3: Set Conditions

For CPU:

  • Threshold: >= 80
  • Period: 5 minutes
  • Evaluation: 2 out of 3

For Storage:

  • Threshold: <= 1000000000 (1 GB)
  • Period: 5 minutes

Step 4: Notifications

  • Choose or create an SNS topic
  • Add your email and confirm the subscription

Step 5: Name & Create

  • Name: HighCPU-RDS, LowStorage-RDS
  • Click Create alarm

βœ… Using AWS CLI

Step 1: Create SNS Topic & Subscribe (if not already done)

aws sns create-topic --name RDSAlerts

aws sns subscribe \
  --topic-arn arn:aws:sns:<region>:<account-id>:RDSAlerts \
  --protocol email \
  --notification-endpoint [email protected]

Step 2: Create High CPU Alarm

aws cloudwatch put-metric-alarm \
  --alarm-name HighCPU-RDS \
  --metric-name CPUUtilization \
  --namespace AWS/RDS \
  --statistic Average \
  --period 300 \
  --threshold 80 \
  --comparison-operator GreaterThanOrEqualToThreshold \
  --evaluation-periods 2 \
  --alarm-actions arn:aws:sns:<region>:<account-id>:RDSAlerts \
  --dimensions Name=DBInstanceIdentifier,Value=my-rds-instance \
  --unit Percent

Step 3: Create Low Storage Alarm

aws cloudwatch put-metric-alarm \
  --alarm-name LowStorage-RDS \
  --metric-name FreeStorageSpace \
  --namespace AWS/RDS \
  --statistic Average \
  --period 300 \
  --threshold 1000000000 \
  --comparison-operator LessThanOrEqualToThreshold \
  --evaluation-periods 2 \
  --alarm-actions arn:aws:sns:<region>:<account-id>:RDSAlerts \
  --dimensions Name=DBInstanceIdentifier,Value=my-rds-instance \
  --unit Bytes

βœ… Challenge 9: Use RDS Snapshot Restore to Clone Your DB into a New Instance

Using AWS Console

Step 1: Go to RDS Console β†’ Snapshots

  • Select a manual or automated snapshot
  • Click Actions β†’ Restore Snapshot

Step 2: Configure the New DB Instance

  • DB instance identifier: clone-mydb
  • DB instance class: e.g., db.t3.medium
  • Storage: Increase size if needed
  • Subnet group: Choose one in the same VPC
  • Public access:
    • ❌ No (for staging/test)
    • βœ… Yes (for external testing)
  • Security group: Allow DB port access from your IP or Bastion

Step 3: Restore

  • Click Restore DB instance
  • Wait until status becomes Available

Step 4: Connect to the New DB

  • Use the new endpoint in tools like psql, mysql, or your app
mysql -h clone-mydb.<xyz>.rds.amazonaws.com -u admin -p

Using AWS CLI:

Step 1: List Available Snapshots

aws rds describe-db-snapshots \
  --db-instance-identifier my-rds-instance
  • Note the DBSnapshotIdentifier, e.g., manual-snapshot-preupgrade

Step 2: Restore Snapshot to New Instance

aws rds restore-db-instance-from-db-snapshot \
  --db-instance-identifier clone-mydb \
  --db-snapshot-identifier manual-snapshot-preupgrade   # manual IDs have no "rds:" prefix (automated ones do) \
  --db-instance-class db.t3.medium \
  --no-publicly-accessible

Step 3: Wait and Connect

aws rds describe-db-instances \
  --db-instance-identifier clone-mydb \
  --query "DBInstances[0].Endpoint.Address"


βœ… Challenge 10: Automate RDS Snapshot Creation Using AWS CLI

Step 1: Create a Manual Snapshot via CLI

aws rds create-db-snapshot \
  --db-instance-identifier my-rds-instance \
  --db-snapshot-identifier my-rds-snapshot-$(date +%Y%m%d-%H%M%S)

This will create a snapshot named like: my-rds-snapshot-20250326-143500

Step 2: Verify the Snapshot

aws rds describe-db-snapshots \
  --db-instance-identifier my-rds-instance \
  --snapshot-type manual \
  --query "DBSnapshots[*].{ID:DBSnapshotIdentifier,Status:Status}" \
  --output table

βœ… Challenge 11: Host a Python App in EC2 with DB (MySQL) in RDS

πŸ’‘ Step 1: Deploy a Simple Flask App on EC2

Launch EC2 Instance:

  • OS: Amazon Linux 2023 / Ubuntu (Amazon Linux 2 reached end of support on June 30, 2026)
  • Type: t3.micro (Free Tier)
  • Security Group:
    • Allow SSH (22) from your IP
    • Allow the app port (8080) from anywhere

Install Python & Flask:

# Amazon Linux 2023
sudo dnf install -y python3 python3-pip git
# Ubuntu: sudo apt update && sudo apt install -y python3-venv git

# A virtualenv avoids "externally-managed-environment" errors on newer distros
python3 -m venv ~/venv && source ~/venv/bin/activate
pip install flask pymysql

Sample Flask App (app.py)

from flask import Flask
import pymysql
import os

app = Flask(__name__)

RDS_HOST = os.environ.get('RDS_HOST', 'your-rds-endpoint.rds.amazonaws.com')
RDS_USER = os.environ.get('RDS_USER', 'admin')
RDS_PASSWORD = os.environ.get('RDS_PASSWORD', 'yourpassword')
RDS_DB = os.environ.get('RDS_DB', 'mydb')

try:
    db = pymysql.connect(
        host=RDS_HOST,
        user=RDS_USER,
        password=RDS_PASSWORD,
        database=RDS_DB,
        connect_timeout=5
    )
    print("βœ… Connected to RDS MySQL successfully.")
except Exception as e:
    print("❌ Failed to connect to RDS MySQL:", e)
    exit()

@app.route('/')
def index():
    return "πŸš€ Flask App is running and connected to RDS!"

@app.route('/add/<name>')
def add_user(name):
    try:
        db.ping(reconnect=True)   # reopen if MySQL closed the idle connection
        with db.cursor() as cursor:
            cursor.execute("INSERT INTO visitors (name) VALUES (%s)", (name,))
            db.commit()
        return f"βœ… Added {name} to the database."
    except Exception as e:
        return f"❌ Failed to insert data: {e}"

@app.route('/users')
def list_users():
    try:
        db.ping(reconnect=True)   # reopen if MySQL closed the idle connection
        with db.cursor() as cursor:
            cursor.execute("SELECT * FROM visitors")
            users = cursor.fetchall()
        return {"users": users}
    except Exception as e:
        return f"❌ Failed to fetch users: {e}"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)   # ports below 1024 need root

Set Environment Variables:

export RDS_HOST=my-rds-instance.abc123.us-east-1.rds.amazonaws.com
export RDS_USER=admin
export RDS_PASSWORD=yourpassword
export RDS_DB=mydb

πŸ’‘ Step 2: Store App Data in Amazon RDS (MySQL)

Launch RDS MySQL Instance:

  • Engine: MySQL
  • Instance: db.t3.micro
  • Storage: 20 GB
  • Public Access: βœ… (or ❌ with Bastion)
  • Security Group: Allow port 3306 from EC2 SG

Create Database & Table:

CREATE DATABASE mydb;
USE mydb;
CREATE TABLE visitors (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100)
);

πŸ’‘ Step 3: Configure CloudWatch Alarms for DB Health

Create Alarms via Console:

  • Go to CloudWatch β†’ Alarms β†’ Create Alarm
  • Metric: RDS β†’ Per-Database Metrics β†’ [your DB]
  • CPUUtilization > 80%
  • FreeStorageSpace < 1 GB
  • Action: Create SNS topic β†’ Add email β†’ Confirm subscription

πŸ’‘ Step 4: Schedule Snapshot & Demonstrate Recovery

Manual Snapshot via CLI:

aws rds create-db-snapshot \
  --db-instance-identifier my-rds-instance \
  --db-snapshot-identifier snapshot-$(date +%Y%m%d-%H%M%S)

Automate with Cron:

crontab -e

Add:

0 3 * * * /home/ec2-user/snapshot.sh >> /home/ec2-user/rds-snapshot.log 2>&1

snapshot.sh Script:

#!/bin/bash
# chmod +x snapshot.sh; the EC2 role needs rds:CreateDBSnapshot
aws rds create-db-snapshot \
  --db-instance-identifier my-rds-instance \
  --db-snapshot-identifier snapshot-$(date +%Y%m%d-%H%M%S)

Restore Snapshot to New DB:

aws rds restore-db-instance-from-db-snapshot \
  --db-instance-identifier my-rds-restore \
  --db-snapshot-identifier snapshot-20250326-030000 \
  --db-instance-class db.t3.micro

πŸ’‘ Step 5: Document & Push to GitHub

  • Create a GitHub repository
  • Add app.py, README.md, and snapshot.sh
  • Push your code using Git
git init
git add .
git commit -m "Initial Flask + RDS deployment"
git remote add origin <your-repo-url>
git push -u origin main


How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #60DaysOfDevOps to engage with the community!



⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post