Join our Newsletter — 33% off our NHI Course
Home› Guides› How to set up automatic rotation in AWS…
Guide Secrets Management

How to set up automatic rotation in AWS Secrets Manager: Managed rotation, Lambda rotation and testing

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 15 min read
On this page

To set up automatic rotation in AWS Secrets Manager, use managed rotation wherever the owning service supports it, build a Lambda rotation function from an AWS template for every other secret, choose single user or alternating users rotation to match the application, and prove each rotation works end to end before you rely on the schedule. Turning rotation on is a few clicks. Making it safe means the function can reach both Secrets Manager and the target, the application picks up the new value, and failures are seen the same day.

This guide is for cloud, platform and application security engineers who own secrets in AWS. It covers choosing between rotation types, the four steps every Lambda rotation function performs, scheduling, networking and permissions, testing, the errors you will meet and how to keep rotation healthy. Finding secrets that are not rotating today is covered separately in How to find unrotated secrets in AWS Secrets Manager; start there if you do not yet have an inventory.

This is an independent guide from NHI Mgmt Group, based on AWS's public documentation as of November 2026. It is not sponsored or reviewed by AWS. Product features change, so confirm settings against AWS's current documentation.

Key takeaways

  • Secrets Manager offers three forms of rotation: managed rotation, managed external secrets rotation for partner-held secrets, and rotation by Lambda function. Only the last needs you to write or deploy code.
  • Managed rotation covers master or admin credentials for Amazon RDS, Aurora, DocumentDB and Redshift, and Private CA certificates for ECS Service Connect. Everything else needs a Lambda function.
  • Every Lambda rotation runs four steps: createSecret, setSecret, testSecret and finishSecret, moving the new value through the AWSPENDING and AWSCURRENT staging labels.
  • Single user rotation suits most cases but has a short window where new credentials may be denied. Alternating users rotation keeps two valid users and suits high-availability applications, at the cost of a superuser secret.
  • Schedules can run as often as every four hours, are set in UTC as rate() or cron() expressions, and run within a rotation window.
  • Most rotation failures are network, KMS or runtime problems, not logic. CloudWatch Logs for the function and RotationFailed events in CloudTrail are where to look.

When you need this

A secret that never changes is a standing credential. If it leaks through a log, a backup, a laptop or a former contractor, it stays valid until someone notices. The OWASP Non-Human Identities Top 10 lists long-lived secrets among its main risks, and rotation is the D3FEND countermeasure D3-CRO, Credential Rotation. Rotation only reduces risk if every consumer moves to the new value and the old one stops working, which is where many programmes fall short; the page on incomplete rotation breaches shows what happens when it does not.

Set up automatic rotation when:

  • An inventory or posture tool reports secrets with rotation disabled or a last-rotated date beyond your policy.
  • Database credentials for applications are created once at launch and never changed.
  • Third-party API keys are stored in Secrets Manager but rotated by hand, if at all.
  • Auditors ask for evidence that credentials are changed on a schedule and after staff changes.
  • You are about to grant a new workload access to a shared secret and want rotation in place first.

Rotation is not always the best answer. If the workload can use IAM authentication, a role or workload identity federation instead of a password, eliminating the secret is stronger than rotating it.

Before you start

  • Classify each secret. Is it a credential the managing service can rotate (for example an RDS master password created with managed credentials), a partner-held secret, a database user you own, or an API key for an external service?
  • Identify the consumers. List every application, job and person that reads the secret, and how they read it: on every connection, at start-up, or through a caching client. An application that reads the secret once at start-up will keep the old value until it restarts.
  • Check the secret structure. AWS rotation templates expect specific JSON keys, such as engine, host, username and password for database secrets. A missing key causes the Key is missing from secret JSON error.
  • Decide the strategy. Single user or alternating users, described below. For alternating users you need a separate secret holding superuser credentials.
  • Map the network path. The rotation function must reach the Secrets Manager endpoint and the target database or service. Note the VPC, subnets, security groups and whether a Secrets Manager interface VPC endpoint exists.
  • Check the KMS key. If the secret is encrypted with a customer managed key, the rotation function's role will need permission to use it.
  • Agree the schedule and window with the application owner, including a time when a short credential change will cause least disruption.

Step-by-step

1. Use managed rotation where it is available

For Aurora, RDS and DocumentDB master user credentials, Redshift admin passwords and ECS Service Connect Private CA certificates, the managing service configures and runs rotation and no Lambda function is involved. You create the secret through the managing service, then control only the schedule. AWS notes that managed rotation typically completes within a minute, and that new connections retrieving the secret during that time may receive the previous credentials.

AWS strongly recommends that applications do not use the master user at all. Create a least-privilege application user, store it in its own secret and rotate that with a Lambda function. Keep the master secret for administration and for alternating users rotation.

2. Choose single user or alternating users rotation

AspectSingle userAlternating users
Users in the secretOne, whose password changes each timeTwo: the original and a clone, alternated each rotation
Superuser secretNot needed, except for Amazon RDS Db2 where users cannot change their own passwordNeeded for most databases, because users cannot clone themselves
During rotationOpen connections stay up; a short window where new logins with the rotated credentials may be deniedBoth users remain valid, so a client that fetches during rotation still gets working credentials
SuitsMost cases, ad hoc and interactive usersHigh-availability applications and owner and accessor role models

With alternating users, the first rotation clones the original user (for example MyUser_clone) with the same permissions it had at that moment. If you later change the original user's grants, you must change the clone's manually, or one rotation in two will leave the application with different permissions. AWS recommends a retry strategy with exponential backoff and jitter for both approaches, because password changes can take time to propagate.

3. Deploy a rotation function from a template

Start from an AWS rotation function template for the secret type, or from the generic template for a custom secret such as a third-party API key. In the console, the rotation configuration for a secret can create the function for you. Infrastructure as code (CloudFormation, the AWS CDK or Terraform) is better for anything beyond a pilot, because the function, its runtime and its permissions then become reviewable.

Secrets Manager invokes the function once per step with a payload containing the step name, the secret ID, a ClientRequestToken and, for assumed-role or cross-account rotation, a RotationToken. The steps are:

  1. createSecret. Checks whether a version with the ClientRequestToken already exists; if not, generates a new value (for example with get_random_password) and stores it as a new version labelled AWSPENDING.
  2. setSecret. Changes the credential in the database or service to match AWSPENDING. AWS advises first checking that AWSCURRENT is valid, that both versions refer to the same user and that the destination host is the same, to guard against confused deputy attacks, and using parameterised queries.
  3. testSecret. Signs in to the target with the AWSPENDING value. AWS templates test with read access.
  4. finishSecret. Moves AWSCURRENT to the new version with update_secret_version_stage. Secrets Manager labels the old version AWSPREVIOUS.

Each step must be safe to retry. If a step fails, Secrets Manager retries the whole rotation several times during open rotation windows. Do not remove the AWSPENDING label with a separate API call during normal operation, because that signals an incomplete rotation.

For custom functions, AWS also advises: never log secret values to CloudWatch Logs; rotate the secret directly in the function, not by calling another Lambda function; package dependencies in the deployment ZIP and keep them patched; use ExcludeCharacters to avoid characters the target rejects; and avoid setting reserved or provisioned concurrency below 10.

4. Give the function network access

A rotation function that cannot reach Secrets Manager or the database simply times out. For a database in a private subnet, place the function in the same VPC, allow outbound traffic from its security group and inbound traffic on the database security group. For Secrets Manager itself, either the function has a route to the public endpoint or you add a Secrets Manager interface VPC endpoint. AWS notes that adding a NAT or internet gateway instead exposes the VPC to more risk, so the endpoint is the preferred option. For alternating users rotation with an RDS-managed superuser secret, the function also needs to reach the RDS API, again through a VPC endpoint.

Check the endpoint's security group allows HTTPS from the function's subnets, that network ACLs permit HTTPS in both directions and that the endpoint policy does not block the function.

5. Set permissions

Secrets Manager must be allowed to invoke the function, and the function's execution role needs permission to read, write and change staging labels on the secrets it rotates, and nothing else. Scope the role to specific secret ARNs or to a tag condition, not to all secrets in the account. If the secret uses a customer managed KMS key, add the key policy statement AWS documents for rotation functions; a missing statement produces Access to KMS is not allowed. For alternating users rotation, the role also needs read access to the superuser secret, and only that one.

6. Turn on rotation and set the schedule

Enable rotation on the secret and attach the function, or confirm managed rotation. Schedules are stored in UTC as rate() or cron() expressions and can run as often as every four hours. The rotation window starts at midnight unless you set a start time, and must not run into the next window. AWS's example rotates a secret between 16:00 and 18:00 UTC on the 1st and 15th of each month:

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
aws secretsmanager rotate-secret \
    --secret-id MySecret \
    --rotation-rules \
        "{\"ScheduleExpression\": \"cron(0 16 1,15 * ? *)\", \"Duration\": \"2h\"}"

For Lambda rotation, add --rotation-lambda-arn with the function ARN. Assume that a rotation may run as soon as rotation is enabled and plan the change for a time when the application owner is watching. Note that if someone updates the secret value manually while rotation is enabled, Secrets Manager counts that as a rotation when it calculates the next date.

As a starting point, NHI Mgmt Group suggests 30 days for application database users with alternating users rotation, 90 days or the provider's limit for third-party API keys that need coordination, and immediate rotation after any suspected exposure or staff departure with access. Set your own schedule from your policy and risk appetite.

7. Make consumers read the current value

Rotation succeeds in Secrets Manager but fails in production if the application holds the old credential. Use a Secrets Manager caching client or the Secrets Manager agent with a cache lifetime shorter than the gap between rotations, retry authentication failures by refreshing the secret, and for single user rotation add backoff and jitter on login. Avoid copying secret values into environment variables at deploy time, which defeats rotation until the next deployment.

Verify it worked

  • Rotate on demand in a test environment and watch CloudWatch Logs for the function. All four steps should be logged in order, with no secret values printed.
  • Check the labels. aws secretsmanager describe-secret should show a new version holding AWSCURRENT, the old one holding AWSPREVIOUS, and no lingering AWSPENDING on a version that is not current.
  • Test the old credential. For single user rotation, the previous password should no longer work. For alternating users, the previous user should still work until the next rotation changes it.
  • Test the application. Confirm it keeps serving requests through the rotation and that new connections use the new value.
  • Check CloudTrail. There should be no RotationFailed events for the secret. Alert on any that appear.
  • Confirm the schedule. describe-secret should show rotation enabled, your rotation rules and a next rotation date that matches your expression.

Rollback and common errors

If a rotation breaks an application, the previous value is still held under AWSPREVIOUS. For alternating users, the previous user is still valid, which is the main operational advantage. For single user rotation, the old password has been replaced in the database, so rollback means moving AWSCURRENT back and resetting the database password to match, or more often fixing the consumer so it reads the new value. If rotation keeps failing, AWS advises clearing a stuck AWSPENDING label and retrying once the cause is fixed. The Secret Rotation Outage Troubleshooting Guide covers incident handling in more depth.

SymptomLikely causeFix
Function log stops after "Found credentials in environment variables", then times outNo route to a Secrets Manager endpointAdd an interface VPC endpoint, or a controlled route to the public endpoint
No activity after createSecretNetwork ACLs, endpoint security group or endpoint policy blocking HTTPS, or Lambda timeout too shortFix the network path and raise the timeout
Access to KMS is not allowedRotation role cannot use the customer managed key, sometimes because of an encryption context conditionApply the documented key policy statement for rotation functions
setSecret: Unable to log into databaseNetwork path to the database (long duration), wrong current credentials (short duration), or an old function that lacks TLS or scram-sha-256 supportFix security groups, test AWSCURRENT manually, or recreate functions set up before late December 2021
Pending secret version "was not created by Lambda"Assumed-role or cross-account rotation without RotationTokenPass RotationToken to put_secret_value
Unable to import module 'lambda_function'Function automatically moved off Python 3.7 without its dependenciesRedeploy the function on Python 3.12 using the method it was created with
Intermittent failures looping between createSecret and setSecretConcurrency set too low, or other writes racing the rotationLeave concurrency unreserved or at least 10, and stop other writes during rotation

Hardening afterwards

  • Find old runtimes. AWS notes that rotation functions created before November 2022 may use Python 3.7, which the AWS SDK for Python stopped supporting in December 2023. Filter Lambda functions for SecretsManager and check the runtime column.
  • Restrict who can disable rotation. Deny secretsmanager:CancelRotateSecret and changes to rotation rules outside the platform team, for example with a service control policy, and alert when rotation is disabled.
  • Restrict access to the rotation function. Whoever can update its code can read every secret it rotates. Treat it as privileged infrastructure.
  • Monitor continuously. Alert on RotationFailed, on secrets whose last rotated date exceeds the schedule and on secrets created without rotation. Track rotation coverage as a metric.
  • Use the clone wisely. In alternating users rotation, keep grants for the original and the clone in step, ideally through a shared database role.
  • Document the runbook. Record owners, schedules, strategy and rollback steps for each secret; the Secrets Rotation Runbook Template provides a format.

Common failure patterns

  • Rotating the master user for the application. The application uses the RDS master password, so a managed rotation interrupts it and the account it uses has far more access than it needs.
  • Rotation enabled, consumers static. The secret rotates on schedule, but services read it once at start-up or from an environment variable, and fail after the next restart or keep using a password that no longer exists.
  • Functions that cannot reach anything. The function is placed in a private subnet with no Secrets Manager endpoint, so every rotation times out and nobody watches CloudTrail.
  • Over-broad rotation roles. One execution role can read and write every secret in the account, turning the function into an attractive target.
  • Drifting clone permissions. Grants are added to the original database user but not the clone, so the application breaks on alternate rotations.
  • Silent failures. Rotation has failed for months, leaving a stuck AWSPENDING version, while dashboards only show that rotation is enabled.
  • Abandoned runtimes. Template functions deployed years ago on an unsupported runtime stop working after a platform upgrade.

Practitioner checklist

  • Every secret classified as managed, partner-held or Lambda-rotated.
  • Applications use least-privilege users, not master or admin credentials.
  • Strategy chosen per secret; alternating users secrets have a dedicated superuser secret.
  • Rotation functions built from AWS templates, deployed as code, on a supported runtime.
  • Functions reach Secrets Manager through an interface VPC endpoint and reach the target through scoped security groups.
  • Execution roles scoped to specific secrets and KMS keys.
  • Schedules and windows agreed with owners, in UTC, no more often than needed.
  • Consumers refresh the secret through a caching client or agent and retry on authentication failure.
  • A test rotation completed with all four steps logged and the application unaffected.
  • Alerts on RotationFailed, disabled rotation and overdue rotation.

Standards and references

Related NHI Mgmt Group resources: How to find unrotated secrets in AWS Secrets Manager · AWS Secrets Manager · Secret Rotation Outage Troubleshooting Guide · Secrets Rotation Runbook Template

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.