Overview

We will:

  1. Choose a Database Engine
  2. Create an AWS RDS Database Instance
  3. Configure Network Settings and Security Groups
  4. Set Up AWS RDS Proxy (Optional but Recommended)
  5. Store Database Credentials Securely with AWS Secrets Manager
  6. Update Lambda Function Configuration
  7. Configure Django to Use the Database
  8. Test the Database Connection
  9. Run Database Migrations
  10. Best Practices and Considerations

Prerequisites


Step 1: Choose a Database Engine

AWS RDS supports several database engines compatible with Django:

For this guide, we’ll use Amazon RDS for PostgreSQL.


Step 2: Create an AWS RDS Database Instance

Option A: Using AWS Management Console

  1. Navigate to RDS Service:

  2. Create a Database:

  3. Choose a Database Creation Method:

  4. Select Engine Options:

  5. Specify Templates:

  6. Settings:

  7. Instance Configuration:

  8. Availability & Durability:

  9. Connectivity:

  10. Additional Configuration:

  11. Backup and Maintenance:

  12. Monitoring:

  13. Log Exports:

  14. Delete Protection:

  15. Create Database:

Option B: Using AWS CLI

aws rds create-db-instance \
    --db-instance-identifier my-django-db \
    --db-instance-class db.t3.micro \
    --engine postgres \
    --allocated-storage 20 \
    --master-username dbadmin \
    --master-user-password YourStrongPassword \
    --vpc-security-group-ids sg-xxxxxxxx \
    --db-subnet-group-name my-subnet-group \
    --no-publicly-accessible

Note: Replace placeholders with your actual values.


Step 3: Configure Network Settings and Security Groups

1. Security Group for RDS

2. Security Group for Lambda Function

3. VPC and Subnets


Benefits:

1. Create RDS Proxy

  1. Navigate to RDS Proxies:

  2. Configure Proxy Settings:

  3. Target Group:

  4. Connectivity:

  5. IAM Role:

  6. Encryption: Enable if required.

  7. Create Proxy:

2. Update Security Groups

3. Adjust Database Connection Settings


Step 5: Store Database Credentials Securely with AWS Secrets Manager

1. Create a Secret

  1. Navigate to Secrets Manager:

  2. Store a New Secret:

  3. Select Database

  4. Secret Name and Description:

  5. Configure Rotation (Optional):

  6. Review and Store:

2. IAM Permissions

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:region:account-id:secret:my-django-db-secret"
    }
  ]
}

Step 6: Update Lambda Function Configuration

1. Configure VPC Access

2. Set Environment Variables

3. Update IAM Role

4. Adjust Timeout and Memory Settings


Step 7: Configure Django to Use the Database

1. Install Database Driver

2. Update settings.py

import os
import json
import boto3
from botocore.exceptions import ClientError

def get_secret():
    secret_name = os.environ.get('SECRET_NAME')
    region_name = os.environ.get('AWS_REGION')

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(service_name='secretsmanager', region_name=region_name)

    try:
        get_secret_value_response = client.get_secret_value(SecretId=secret_name)
    except ClientError as e:
        raise e
    else:
        # Secrets Manager returns the secret as a string
        secret = get_secret_value_response['SecretString']
        return json.loads(secret)

secrets = get_secret()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': secrets['dbname'],
        'USER': secrets['username'],
        'PASSWORD': secrets['password'],
        'HOST': secrets['host'],  # Use RDS Proxy endpoint if using proxy
        'PORT': secrets.get('port', '5432'),
    }
}

Notes:


Step 8: Test the Database Connection

1. Verify Lambda Function Connectivity

2. Check CloudWatch Logs

3. Common Issues


Step 9: Run Database Migrations

Option 1: Run Migrations via Lambda Function

Option 2: Run Migrations Locally

Note: Ensure your local environment can access the database.


Step 10: Best Practices and Considerations

1. Database Connection Management

2. Security

3. Performance Optimization

4. Monitoring and Logging

5. Cost Management


Additional Tips


Conclusion

By following these steps, you’ve set up an AWS RDS database instance configured to work with your Lambda function running a Django application. This setup ensures secure, scalable, and efficient database connectivity in a serverless environment.