DEV Community

gurpreet kaur
gurpreet kaur

Posted on

🔐 Securing Amazon RDS Credentials with AWS Secrets Manager

In cloud-native environments, secrets management is critical. Hardcoding database credentials or API keys within code repositories is not only bad practice—it’s a serious security risk. In this guide, I’ll walk you through how to securely manage Amazon RDS credentials using AWS Secrets Manager, including automatic secret rotation with AWS Lambda.

As part of my hands-on learning, I implemented this solution to secure database credentials for an application deployed in AWS Lambda. This walkthrough covers storing, retrieving, and rotating secrets using native AWS integrations—enabling secure, uninterrupted database connectivity.

🔧 Why Use AWS Secrets Manager?
AWS Secrets Manager allows you to:

  • Securely store and encrypt secrets (e.g., database credentials).
  • Programmatically retrieve secrets via applications or scripts.
  • Enable automated rotation of secrets to meet compliance needs.
  • Eliminate hardcoded secrets in your codebase.

🧩 Architecture Overview
Here’s what the architecture looks like:

  • Application runs inside AWS Lambda.
  • Lambda retrieves secrets from AWS Secrets Manager.
  • Secret contains RDS credentials and is set up for automated rotation.
  • Rotation is handled using another Lambda function.
  • Interface VPC Endpoints are used to securely access Secrets Manager inside the VPC.

🪜 Step-by-Step Implementation
Step 1: Launch an RDS Instance

  • Create an Amazon RDS (MySQL/Aurora) instance.
  • Ensure the Security Group attached to the instance allows inbound traffic on TCP port 3306 (MySQL/Aurora default).
  • Note down the DB endpoint and credentials (we'll use them in the secret).

Step 2: Store Credentials in AWS Secrets Manager

  • Go to AWS Secrets Manager > Store a new secret.
  • Choose Credentials for RDS database.
  • Add the database username, password, and connection details.
  • Provide an encryption key (KMS) and link to the RDS database from Step1.
  • Name your secret (e.g., MyRDS/ProdApp).

Step 3: Create a VPC Interface Endpoint

  • Navigate to VPC > Endpoints > Create Endpoint.
  • Choose com.amazonaws.region.secretsmanager.
  • Select the VPC and subnets from each AZ.
  • Attach a Security Group that allows Lambda functions in the VPC to access the endpoint.

This enables AWS PrivateLink connectivity to Secrets Manager.

Step 4: Create a Lambda to Retrieve Secrets

  • Create a Lambda function inside the same VPC.
  • Attach IAM permissions: secretsmanager:GetSecretValue, rds:Connect.
  • Install PyMySQL library via Lambda layers or zip package.

Sample code snippet:

import boto3
import pymysql
import json
import os

def lambda_handler(event, context):
    secret_name = os.environ['SECRET_NAME']
    region = os.environ['AWS_REGION']
    client = boto3.client('secretsmanager', region_name=region)
    response = client.get_secret_value(SecretId=secret_name)
    secret = json.loads(response['SecretString'])

    connection = pymysql.connect(
        host=secret['host'],
        user=secret['username'],
        password=secret['password'],
        db='your_db_name',
        port=3306
    )
    print("Connection successful!")
Enter fullscreen mode Exit fullscreen mode

Test the Lambda to ensure it connects to RDS using the secret.

Step 5: Set Up Rotation Lambda

  • Create a second Lambda function to handle rotation logic.

This function follows four steps:

  • createSecret: Generate new credentials.
  • setSecret: Update credentials in the RDS DB.
  • testSecret: Test connectivity.
  • finishSecret: Promote new secret to current.

Grant the following resource-based policy:

{
  "Sid": "secret-rotation",
  "Effect": "Allow",
  "Principal": {
    "Service": "secretsmanager.amazonaws.com"
  },
  "Action": "lambda:InvokeFunction",
  "Resource": "arn:aws:lambda:region:account-id:function:rotation-function-name"
}
Enter fullscreen mode Exit fullscreen mode

Add the PyMySQL layer as a custom Lambda layer.

Step 6: Enable Secret Rotation

  • Go to the secret created in Step 2.
  • Enable automatic rotation.
  • Assign the Lambda rotation function from Step 5.
  • Choose a rotation interval (e.g., every 30 days).

Step 7: Test Secret Rotation

  • Trigger a manual rotation.
  • Check logs in CloudWatch Logs.
  • Confirm: Secret is rotated.
  • Lambda rotation function updated the RDS database.
  • Your application still connects successfully using new credentials.

🧪 Validating Rotation via AWS CLI
You can also retrieve secrets using the CLI:

aws secretsmanager get-secret-value --secret-id MyRDS/ProdApp
Enter fullscreen mode Exit fullscreen mode

🔄 How Secret Rotation Works (Under the Hood)
AWS Secrets Manager uses Lambda and version labels:

AWSPENDING: New version created by rotation function.
AWSCURRENT: Active version used by applications.
AWSPREVIOUS: Previous version before rotation.

Each rotation function must:
Generate new credentials.
Update the RDS DB.
Test connectivity.
Finalize the rotation and update version labels.

✅ Benefits of This Approach
✔ No hardcoded credentials in code
✔ Automated compliance with rotation policies
✔ Reduced risk of credential leakage
✔ Secure, programmatic access to secrets from inside VPC
✔ Seamless integration with Lambda and RDS

📝 Final Thoughts
Secrets management isn’t just a best practice—it’s a necessity. AWS Secrets Manager, coupled with Lambda and RDS, provides a powerful solution to automate secret handling and reduce security risks.

I’ve personally implemented this solution to securely manage database access for cloud applications—and it's become a foundational security building block in my AWS learning journey.

🔒 Stay secure, automate wisely, and always validate with logs!
Let me know in comments if you’ve tried this or plan to implement it.

Top comments (0)