Database SRE

Database Connection String Security: Secrets Managers and Credential Rotation

Secure database credentials with AWS Secrets Manager, automatic rotation, Kubernetes secrets, and git-secrets scanning. Never hardcode connection strings.

JusDB Team
July 21, 2025
Updated May 10, 2026
5 min read
168 views

Database credentials in connection strings are a leading cause of data breaches. Here is how to manage them securely across different environments and deployment patterns.

Never Hardcode Credentials

python
# BAD: credentials in source code
conn = psycopg2.connect('postgresql://admin:password@db:5432/mydb')

# GOOD: credentials from environment
import os
conn = psycopg2.connect(
    host=os.environ['DB_HOST'],
    user=os.environ['DB_USER'],
    password=os.environ['DB_PASSWORD'],
    dbname=os.environ['DB_NAME'],
    sslmode='require'
)

AWS Secrets Manager Integration

python
import boto3, json

def get_db_credentials(secret_name: str) -> dict:
    client = boto3.client('secretsmanager', region_name='us-east-1')
    secret = client.get_secret_value(SecretId=secret_name)
    return json.loads(secret['SecretString'])

creds = get_db_credentials('prod/myapp/postgres')
conn = psycopg2.connect(
    host=creds['host'],
    user=creds['username'],
    password=creds['password'],
    dbname=creds['dbname'],
    sslmode='require'
)

Automatic Secrets Rotation

bash
# Enable automatic rotation every 30 days
aws secretsmanager rotate-secret \
  --secret-id prod/myapp/postgres \
  --rotation-lambda-arn arn:aws:lambda:...:SecretsManagerRDSRotation \
  --rotation-rules AutomaticallyAfterDays=30

Kubernetes: Use Secrets, Not ConfigMaps

yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
stringData:
  DB_PASSWORD: "$(vault kv get -field=password secret/myapp/db)"

---
# Reference in Pod spec
env:
  - name: DB_PASSWORD
    valueFrom:
      secretKeyRef:
        name: db-credentials
        key: DB_PASSWORD

Scan for Leaked Credentials

bash
# Use git-secrets to prevent committing credentials
git secrets --install
git secrets --register-aws

# Or use trufflehog to scan history
trufflehog git file://./myrepo --only-verified

Key Takeaways

  • Never hardcode database credentials — always load from environment variables or secrets managers
  • Use AWS Secrets Manager or HashiCorp Vault with automatic rotation
  • Always include sslmode=require in connection strings to prevent credential interception
  • Scan your git history for leaked credentials — it happens more often than you think

JusDB Can Help

Credential management is a critical security control. JusDB can review your secrets management practices and implement rotation policies.

Share this article

JusDB Team

Official JusDB content team

Need Expert Help?

Need expert help? Our specialists can assist with these related services: