AWS Secrets Manager: Secrets Lifecycle, Automatic Rotation, and Cross-Service Integration

The credential that compromises a production database is almost never obtained through a sophisticated attack. It is the one hardcoded in a configuration file, checked into a private GitHub repository that became public, or stored in an environment variable that showed up in an error log. These are not edge cases. They are standard failure modes that repeat across organizations at every scale.

AWS Secrets Manager eliminates these failure modes by centralizing credential storage, automating rotation on a schedule, and giving applications a secure API to retrieve current credentials at runtime. In this article I will walk through storing and retrieving secrets, configuring automatic rotation for RDS credentials, cross-account access patterns, and the application code that uses Secrets Manager correctly.

Storing Secrets with Terraform

resource "aws_secretsmanager_secret" "database" {
  name                    = "/production/order-service/database"
  description             = "PostgreSQL credentials for order-service production database"
  kms_key_id              = aws_kms_key.secrets.arn
  recovery_window_in_days = 7

  tags = {
    Service     = "order-service"
    Environment = "production"
    Rotation    = "automatic"
  }
}

resource "aws_secretsmanager_secret_version" "database" {
  secret_id = aws_secretsmanager_secret.database.id

  secret_string = jsonencode({
    username = "order_service"
    password = random_password.database.result
    host     = aws_db_instance.main.address
    port     = 5432
    dbname   = "orders"
    engine   = "postgres"
  })

  lifecycle {
    ignore_changes = [secret_string]
  }
}

resource "random_password" "database" {
  length           = 32
  special          = true
  override_special = "!#$%&*()-_=+[]{}:?"
}

resource "aws_secretsmanager_secret" "api_key" {
  name                    = "/production/order-service/payment-api-key"
  description             = "Payment processor API key"
  kms_key_id              = aws_kms_key.secrets.arn
  recovery_window_in_days = 30
}

The lifecycle block with ignore_changes = [secret_string] is critical. Secrets Manager rotation updates the secret value directly. Without this lifecycle block, the next terraform apply would overwrite the rotated secret with the original value, breaking the rotation cycle and potentially locking out your application. Once a secret is created and the initial value is set, ignore_changes ensures Terraform manages the secret’s metadata but not its value.

Automatic Rotation for RDS Credentials

resource "aws_secretsmanager_secret_rotation" "database" {
  secret_id           = aws_secretsmanager_secret.database.id
  rotation_lambda_arn = aws_lambda_function.rotation.arn

  rotation_rules {
    automatically_after_days           = 30
    duration                           = "2h"
    schedule_expression                = "cron(0 3 1 * ? *)"
  }
}

resource "aws_lambda_function" "rotation" {
  function_name = "rds-secret-rotation"
  role          = aws_iam_role.rotation_lambda.arn
  handler       = "lambda_function.lambda_handler"
  runtime       = "python3.12"
  filename      = "rotation_function.zip"
  timeout       = 30

  vpc_config {
    subnet_ids         = var.private_subnet_ids
    security_group_ids = [aws_security_group.rotation.id]
  }

  environment {
    variables = {
      SECRETS_MANAGER_ENDPOINT = "https://secretsmanager.${var.region}.amazonaws.com"
    }
  }
}

AWS provides pre-built rotation Lambda functions for RDS, Redshift, and DocumentDB through the Serverless Application Repository. For RDS, there are two rotation strategies: single-user rotation changes the password for the same user, and multi-user rotation alternates between two users, keeping the previous user valid until all active connections using it have closed. Multi-user rotation is zero-downtime for applications that do not cache database connections across rotation events.

The schedule_expression overrides automatically_after_days when specified. Use cron expressions to rotate at low-traffic times rather than at a random time after N days. The duration = 2h gives the rotation Lambda up to 2 hours to complete the rotation before Secrets Manager considers it failed.

Application Integration

import boto3
import json
from functools import lru_cache
import time

class SecretsClient:
    def __init__(self, region: str = "us-east-1"):
        self._client  = boto3.client("secretsmanager", region_name=region)
        self._cache   = {}
        self._ttl     = 300

    def get_secret(self, secret_name: str) -> dict:
        now = time.time()

        if secret_name in self._cache:
            secret, expires_at = self._cache[secret_name]
            if now  str:
        secret = self.get_secret(secret_name)
        return (
            f"postgresql://{secret['username']}:{secret['password']}"
            f"@{secret['host']}:{secret['port']}/{secret['dbname']}"
        )

secrets_client = SecretsClient()

def get_db_connection():
    conn_string = secrets_client.get_database_connection_string(
        "/production/order-service/database"
    )
    return psycopg2.connect(conn_string)

The 300-second cache (5 minutes) balances performance against rotation responsiveness. An application that calls GetSecretValue on every database connection pays the API call cost and adds latency to every query. A cache that is too long means the application continues using rotated-away credentials after rotation completes, causing connection failures until the cache expires. Five minutes is the standard recommendation for most rotation windows.

When a database connection fails with an authentication error, invalidate the cache for that secret and retry with fresh credentials. This handles the transition period during rotation when the old password is still valid but the Secrets Manager value has been updated to the new password.

Cross-Account Access

resource "aws_secretsmanager_secret_policy" "cross_account" {
  secret_arn = aws_secretsmanager_secret.database.arn

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid    = "AllowCrossAccountAccess"
        Effect = "Allow"
        Principal = {
          AWS = [
            "arn:aws:iam::${var.application_account_id}:role/order-service-role"
          ]
        }
        Action = [
          "secretsmanager:GetSecretValue",
          "secretsmanager:DescribeSecret"
        ]
        Resource = "*"
      },
      {
        Sid    = "AllowKMSDecrypt"
        Effect = "Allow"
        Principal = {
          AWS = "arn:aws:iam::${var.application_account_id}:role/order-service-role"
        }
        Action   = ["kms:Decrypt", "kms:DescribeKey"]
        Resource = aws_kms_key.secrets.arn
      }
    ]
  })
}

The resource policy alone is not sufficient for cross-account access. The KMS key policy must also allow the consuming account’s role to decrypt, since the secret is encrypted with the KMS key. Both the secret policy and the KMS key policy must grant access for the cross-account pattern to work. Forgetting the KMS key policy is the most common reason cross-account secret access fails despite a correctly configured resource policy.

Closing Thoughts

Secrets Manager solves credential management correctly. Secrets are never in source code, environment variables, or configuration files. Rotation happens automatically on a schedule without application deployments. Access is controlled through IAM policies and audited through CloudTrail. The 5-minute caching pattern keeps API costs negligible while handling rotation gracefully.

Migrate all hardcoded credentials to Secrets Manager as a first-priority security initiative if you have not already. Enable automatic rotation for every database credential and every API key that the credential provider supports rotation for. Use the resource policy pattern for cross-account access rather than sharing credential values out-of-band. These three practices eliminate the credential management debt that most AWS environments carry.

Enjoy the cloud.

Osama


#AWS #SecretsManager #CloudSecurity #CredentialManagement #CloudArchitecture #Terraform #InfrastructureAsCode #AmazonWebServices #SolutionsArchitect #CloudComputing #SecretRotation #IAM #KMS #TechBlog #CloudInfrastructure #DevSecOps #DatabaseSecurity #Compliance #ZeroTrust #Engineering

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.