AWS Secrets Manager: The Complete Security Credentials Cheatsheet

Introduction

AWS Secrets Manager is a service that helps you protect secrets needed to access your applications, services, and IT resources. It enables you to easily rotate, manage, and retrieve database credentials, API keys, and other secrets throughout their lifecycle. By using Secrets Manager, you can replace hardcoded credentials in your code with API calls to retrieve secrets programmatically.

Core Concepts

Secret Types

  • Database credentials: RDS, Redshift, DocumentDB
  • API keys: Third-party services
  • OAuth tokens: Application authentication
  • Arbitrary text: Any sensitive data stored as text/JSON
  • Binary data: Certificates, private keys

Key Features

  • Centralized storage: Single service for all secrets
  • Encryption: All secrets encrypted at rest with AWS KMS
  • Rotation: Automated secret rotation with Lambda
  • Fine-grained access: IAM policies to control access
  • Auditing: Integration with CloudTrail for logging
  • Regional replication: For high availability

Working with AWS Secrets Manager

Creating and Managing Secrets

ActionAWS ConsoleAWS CLIAWS SDK
Create SecretSecrets Manager > Store a new secretaws secretsmanager create-secretCreateSecret API
Update SecretSelect secret > Editaws secretsmanager update-secretUpdateSecret API
Delete SecretSelect secret > Deleteaws secretsmanager delete-secretDeleteSecret API
Restore SecretDeleted tab > Restoreaws secretsmanager restore-secretRestoreSecret API

CLI Commands for Managing Secrets

# Create a new secret
aws secretsmanager create-secret \
    --name MySecret \
    --description "My test secret" \
    --secret-string '{"username":"admin","password":"t0p-S3cret!"}'

# Retrieve a secret
aws secretsmanager get-secret-value --secret-id MySecret

# Update a secret's value
aws secretsmanager update-secret \
    --secret-id MySecret \
    --secret-string '{"username":"admin","password":"n3w-S3cret!"}'

# Delete a secret (with recovery window)
aws secretsmanager delete-secret \
    --secret-id MySecret \
    --recovery-window-in-days 7

# Delete a secret (without recovery)
aws secretsmanager delete-secret \
    --secret-id MySecret \
    --force-delete-without-recovery

# List all secrets
aws secretsmanager list-secrets

Secret Rotation

Rotation Methods

  1. Automated rotation: Using Lambda functions
  2. Manual rotation: Update secrets using API/console

Setting Up Automated Rotation

  1. Create a Lambda function for rotation logic
  2. Configure rotation in Secrets Manager console
  3. Set rotation schedule (15-365 days)
  4. Define rotation Lambda function

Rotation Lambda Examples

  • Single-user rotation: Changes password for same user
  • Alternate-user rotation: Creates new user, swaps credentials, deletes old user

Accessing Secrets

Code Examples

Python (boto3)

import boto3
import json

def get_secret(secret_name, region_name="us-east-1"):
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )
    
    response = client.get_secret_value(SecretId=secret_name)
    secret = response['SecretString']
    return json.loads(secret)

# Usage
credentials = get_secret("db/production/postgresql")
username = credentials["username"]
password = credentials["password"]

JavaScript (AWS SDK)

const AWS = require('aws-sdk');
const secretsManager = new AWS.SecretsManager({
  region: 'us-east-1'
});

async function getSecret(secretName) {
  try {
    const data = await secretsManager.getSecretValue({ SecretId: secretName }).promise();
    if ('SecretString' in data) {
      return JSON.parse(data.SecretString);
    }
  } catch (err) {
    console.error(`Error retrieving secret: ${err.message}`);
    throw err;
  }
}

// Usage
getSecret('db/production/postgresql')
  .then(credentials => {
    const { username, password } = credentials;
    // Use the credentials
  });

IAM Permissions and Security

Key IAM Actions

  • secretsmanager:CreateSecret
  • secretsmanager:GetSecretValue
  • secretsmanager:UpdateSecret
  • secretsmanager:DeleteSecret
  • secretsmanager:RotateSecret
  • secretsmanager:TagResource

Example IAM Policy (Read-only access)

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetSecretValue",
        "secretsmanager:DescribeSecret",
        "secretsmanager:ListSecrets"
      ],
      "Resource": "arn:aws:secretsmanager:*:*:secret:*"
    }
  ]
}

Secret Resource Policy Example

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/ApplicationRole"
      },
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "*"
    }
  ]
}

Integration with AWS Services

ServiceIntegration TypePurpose
RDSNativeStore and rotate database credentials
LambdaEnvironment VariablesSecurely access secrets at runtime
ECS/EKSContainer SecretsInject secrets as environment variables
CloudFormationDynamic ReferencesReference secrets in templates
Parameter StoreCross-referencesLink to secrets from Parameter Store
CloudTrailAuditingTrack API calls to Secrets Manager

Best Practices

Security

  • Use least privilege IAM policies
  • Enable automatic rotation for all secrets
  • Use VPC endpoints to access Secrets Manager privately
  • Implement resource policies for cross-account access
  • Leverage AWS KMS custom keys for additional control

Cost Optimization

  • Store related secrets as a single JSON object
  • Use Parameter Store for non-sensitive configuration
  • Be mindful of rotation frequency (affects API calls)
  • Monitor usage with CloudWatch

Operations

  • Use tags to organize and manage secrets
  • Implement secret versioning for auditing
  • Create standardized naming conventions
  • Set up CloudWatch alarms for failed rotations
  • Use resource-based policies for cross-account sharing

Common Challenges and Solutions

ChallengeSolution
Cost managementUse Parameter Store for non-sensitive data; batch related secrets
Cross-account accessImplement resource policies to grant specific permissions
Rotation failuresSet up CloudWatch alarms; test rotation Lambda functions thoroughly
Secret versioningUse staging labels to manage secret versions
Bulk operationsUse AWS CLI with scripts for bulk management

Troubleshooting

Common Issues

  1. Permission errors: Check IAM policies and resource policies
  2. Rotation failures: Verify Lambda execution role and network access
  3. Throttling: Implement exponential backoff for API calls
  4. Cross-region access: Use regional endpoints or replicate secrets
  5. VPC connectivity: Ensure proper VPC endpoint configuration

Pricing (as of October 2024)

  • Secret storage: $0.40 per secret per month
  • API calls: $0.05 per 10,000 API calls
  • Secret rotation: Standard Lambda pricing applies

Resources for Further Learning

Scroll to Top