Sub topic 9
Rotating secrets automatically
This chapter assumes you have read the earlier chapters on Secrets Manager basics, versions and staging labels, and IAM access. You should be comfortable with AWSCURRENT and AWSPREVIOUS, and you should know how to invoke a Lambda function.
What rotation does
Rotation replaces a secret's value on a schedule. It changes the credential in two places: in the system that accepts it, such as a database, and in the stored secret. Short-lived credentials limit the damage of a leak, and a rotation you run routinely is one you know works when you need it in an emergency.
Secrets Manager supports rotation. Parameter Store does not. If you need scheduled rotation for a SecureString parameter, you must build the schedule and the credential change yourself. This is one of the main reasons to choose Secrets Manager.
How a rotation runs
Secrets Manager does not change credentials itself. It invokes a Lambda function, called the rotation function, once for each of four steps. Each invocation receives an event with three fields:
SecretId: the secret's ARN.ClientRequestToken: the ID of the new secret version.Step: one ofcreateSecret,setSecret,testSecret, orfinishSecret.
The steps work with staging labels as follows:
createSecretgenerates a new value and saves it as a new version labeledAWSPENDING. Applications still readAWSCURRENT, so nothing changes for them.setSecretchanges the credential in the target system to the pending value.testSecretauthenticates with the pending value to prove it works.finishSecretmovesAWSCURRENTto the new version. The old version receivesAWSPREVIOUS.
If any step raises an error, rotation stops. AWSCURRENT is never moved, so applications keep the last working value. Secrets Manager retries the rotation later.
Each step must be idempotent. Secrets Manager can invoke a step more than once, and the function must produce the same end state on every call. The ClientRequestToken is what makes this possible: it identifies one rotation attempt, so a repeated createSecret call can detect that the pending version already exists.
Rotation strategies
Rotating a database user's own password creates a gap. Between setSecret and finishSecret, the database accepts the new password while applications may still hold the old one. The two common strategies handle that gap differently.
| Strategy | How it works | Trade-off |
|---|---|---|
| Single user | Changes the password of one database user. | Simple. Connections that opened with the old password usually stay valid, but new connections made with a cached old value can fail briefly. |
| Alternating users | Keeps two users, such as `app` and `app_clone`. Each rotation updates the user that is not current, then switches. | No gap, because the previous credential stays valid for a full cycle. It needs a second user and a superuser secret. |
For a service that does not tolerate failed logins, use alternating users. For most internal applications with retry logic, single user is enough.
Enabling rotation
For supported databases, you do not need to write the function. AWS provides rotation function templates for Amazon RDS, Amazon Aurora, Amazon DocumentDB, and Amazon Redshift. Some services also offer managed rotation, in which the owning service runs rotation for you and there is no Lambda function in your account. For other secret types, such as third-party API keys, you write the function.
First, allow Secrets Manager to invoke the function:
aws lambda add-permission \
--function-name myapp-db-rotation \
--statement-id SecretsManagerAccess \
--action lambda:InvokeFunction \
--principal secretsmanager.amazonaws.comThen attach the function to the secret and set a schedule:
aws secretsmanager rotate-secret \
--secret-id myapp/prod/db \
--rotation-lambda-arn arn:aws:lambda:us-east-1:111122223333:function:myapp-db-rotation \
--rotation-rules AutomaticallyAfterDays=30AutomaticallyAfterDays accepts values from 1 to 1000. For finer control, use ScheduleExpression with a rate() or cron() expression and an optional Duration that sets the window in which rotation may start:
aws secretsmanager rotate-secret \
--secret-id myapp/prod/db \
--rotation-rules '{"ScheduleExpression":"cron(0 4 ? * SAT *)","Duration":"2h"}'By default, rotate-secret starts a rotation immediately, in addition to setting the schedule. Expect your first rotation to happen as soon as you run the command, so check that applications can handle it first. Pass --no-rotate-immediately to wait for the first scheduled time.
You can also define rotation in CloudFormation. The HostedRotationLambda property deploys an AWS-provided rotation function for you:
Resources:
DbRotation:
Type: AWS::SecretsManager::RotationSchedule
Properties:
SecretId: !Ref DbSecret
HostedRotationLambda:
RotationType: MySQLSingleUser
RotationLambdaName: myapp-db-rotation
RotationRules:
AutomaticallyAfterDays: 30The secret in SecretId must already be attached to the database, for example through AWS::SecretsManager::SecretTargetAttachment, so the function knows where to connect.
Writing a rotation function
If you rotate something other than a supported database, you implement the four steps yourself. The skeleton below shows the dispatch logic and two complete steps, createSecret and finishSecret. The steps that talk to the target system are left as stubs because they depend on the system. Replace both stubs before use, or rotation will report success without changing anything.
import json
import logging
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client("secretsmanager")
def lambda_handler(event, context):
arn = event["SecretId"]
token = event["ClientRequestToken"]
step = event["Step"]
meta = client.describe_secret(SecretId=arn)
if not meta.get("RotationEnabled"):
raise ValueError(f"Rotation is not enabled for {arn}")
stages = meta["VersionIdsToStages"]
if token not in stages:
raise ValueError(f"Version {token} has no stage for {arn}")
if "AWSCURRENT" in stages[token]:
logger.info("Version %s is already current", token)
return
if "AWSPENDING" not in stages[token]:
raise ValueError(f"Version {token} is not AWSPENDING")
if step == "createSecret":
create_secret(arn, token)
elif step == "setSecret":
set_secret(arn, token)
elif step == "testSecret":
test_secret(arn, token)
elif step == "finishSecret":
finish_secret(arn, token)
else:
raise ValueError(f"Unknown step {step}")
def create_secret(arn, token):
try:
client.get_secret_value(
SecretId=arn, VersionId=token, VersionStage="AWSPENDING"
)
return # already created by an earlier attempt
except client.exceptions.ResourceNotFoundException:
pass
current = json.loads(
client.get_secret_value(SecretId=arn, VersionStage="AWSCURRENT")["SecretString"]
)
current["password"] = client.get_random_password(
PasswordLength=32, ExcludeCharacters="/@\"'\\"
)["RandomPassword"]
client.put_secret_value(
SecretId=arn,
ClientRequestToken=token,
SecretString=json.dumps(current),
VersionStages=["AWSPENDING"],
)
def set_secret(arn, token):
# Stub: change the credential in the target system to the AWSPENDING value.
raise NotImplementedError("Implement for your target system")
def test_secret(arn, token):
# Stub: authenticate to the target system with the AWSPENDING value.
raise NotImplementedError("Implement for your target system")
def finish_secret(arn, token):
meta = client.describe_secret(SecretId=arn)
current_version = None
for version, stages in meta["VersionIdsToStages"].items():
if "AWSCURRENT" in stages:
if version == token:
return
current_version = version
break
client.update_secret_version_stage(
SecretId=arn,
VersionStage="AWSCURRENT",
MoveToVersionId=token,
RemoveFromVersionId=current_version,
)The function's execution role needs secretsmanager:DescribeSecret, GetSecretValue, PutSecretValue, and UpdateSecretVersionStage on the secret, plus secretsmanager:GetRandomPassword. It also needs kms:Decrypt and kms:GenerateDataKey if the secret uses a customer managed key.
Common failures
- The function cannot reach the database or Secrets Manager. A function placed in a VPC needs a route to the database and a route to the Secrets Manager endpoint, either through a VPC interface endpoint or a NAT gateway.
- Secrets Manager cannot invoke the function. The resource policy from
add-permissionis missing. CloudFormation and the console add it for you, but the CLI does not. - Applications fail after rotation. They cached the old value for longer than the previous credential stays valid. Set your cache time-to-live shorter than the rotation window, and make your client re-fetch the secret and retry once after an authentication error.
- The secret is stuck in a failed state. A failed rotation leaves an orphaned
AWSPENDINGversion. The next rotation reuses or replaces it, so check the function's CloudWatch logs for the real error before retrying withrotate-secret. - Another service holds a copy. Rotation updates only the secret. If you copied the password into an environment variable or a config file, that copy goes stale.
To confirm rotation is working, inspect the secret:
aws secretsmanager describe-secret --secret-id myapp/prod/db \
--query '{Enabled:RotationEnabled,Last:LastRotatedDate,Next:NextRotationDate,Stages:VersionIdsToStages}'Exercise
A rotation run fails at the testSecret step. Which version do applications that request the AWSCURRENT stage receive, and why?
Show answer
They receive the old version. The new value exists only under AWSPENDING until finishSecret moves AWSCURRENT, and finishSecret never runs after a failed step. Applications therefore keep reading the last value that worked.
Exercise
Your application cannot tolerate even one failed login during rotation. Which strategy do you choose, and what does it cost you?
Show answer
Alternating users. The previous credential stays valid for a full rotation cycle, so applications holding it are not locked out. The cost is a second database user and an additional superuser secret that the rotation function uses to change the passwords.
Exercise
You ran rotate-secret with AutomaticallyAfterDays=30 and a rotation started at once. How do you avoid that next time?
Show answer
Add --no-rotate-immediately. The schedule is still set, and the first rotation happens at the next scheduled time.