Bootstrap FreeKB - Amazon Web Services (AWS) - Getting Started with Secrets Rotation
Amazon Web Services (AWS) - Getting Started with Secrets Rotation


Rotating a secret basically means:

  1. Create a new version of the secret
  2. Update the value of the keys in the secret

For example, let's say you have a secret named my-secret that contains two key/value pairs.

 

This could also be seen with the aws secretsmanager get-secret-value command.

~]$ aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret-tD1U2U
{
    "ARN": "arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret-tD1U2U",
    "Name": "my-secret",
    "VersionId": "0a8aa38f-b95e-42ab-acc9-7745aa710f23",
    "SecretString": "{\"username\":\"john.doe\",\"password\":\"itsasecret\"}",
    "VersionStages": [
        "AWSCURRENT"
    ],
    "CreatedDate": "2023-08-23T22:23:54.737000+00:00"
}

 

Since the first step in rotating a secret is to create a new version of the secret, let's take a look at the versions that my-secret has. In this example, my-secret has a single version (because I just created the secret).

 

By default, Secrets will have Rotation disabled, which can be seen in the AWS Secrets console by selecting one of your secrets and going to the Rotation tab.

 

The aws secretsmanager put-secret-value command with the --version option can be used to create a new version of the secret.

aws secretsmanager put-secret-value \
--secret-string "{\"username\":\"john.doe\",\"password\":\"mynewpassword\"}" \
--secret-id arn:aws:secretsmanager:us-east-1:123456789012:secret:my-secret-SgNa1s \
--version 2

 

There should now be two versions of my-secret. By default, we a secret is rotated

  • The new version of the secret will have Staging Label AWSCURRENT
  • The prior version of the secret will have Staging Label AWSPREVIOUS

 

Of course, you are not going to want to have to manually go into the AWS console or manually issue AWS CLI commands to rotate a secret. Instead, secrets can be automatically rotated via a Lambda Function. For example, just to keep this super duper simple, here is one of my boilerplate Lambda functions to rotate a secret. Of course, you would want a much more mature Lambda Function. Again, this is just a simple Getting Started article, hence this very minimal Lambda Function.

Notice this uses uuid to generate a Universal Unique IDentifier (UUID), something like 0e8f48b1-4932-40b5-8d48-7e60f98335ea. The new version of the secret AWSCURRENT should have the new UUID.

import json
import boto3
import uuid

def lambda_handler(event, context):
    
    client = boto3.client('secretsmanager')

    secrets_dict = client.list_secrets(
        Filters = [
            { 'Key': 'name', 'Values': ['my-secret'] }
        ]
    )

    client_request_token = str(uuid.uuid4())

    print(f"client_request_token = {client_request_token}")
    
    for secret in secrets_dict['SecretList']:
        client.put_secret_value(
            SecretId=secret['ARN'],
            ClientRequestToken=client_request_token,
            SecretString='{"username":"john.doe","password":"mynewpassword"}'
    )
    
    
    return {
        'statusCode': 200,
        'body': json.dumps('lookin good')
    }

 

Your Lambda Function will need to be updated with a resource-based Policy Permission that allows Secrets Manager to invoke the Lambda Function.

 

Or, the aws lambda add-permission command can be used.

aws lambda add-permission \
--function-name <the ARN of your Lambda Function> \
--action lambda:InvokeFunction \
--statement-id SecretsManagerAccess

 

And the IAM Role attached to your Lambda Function will need to allow certain Secret Manager Policy Permissions.  For example, you could attach the SecretManagerReadWrite Policy Permission to the IAM Role attached to your Lambda Function.

 

Or, the aws iam attach-role-policy command can be used.

aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/SecretManagerReadWrite \
--role-name my-role

 

And then last but not least, on the Rotation Tab for your secret, you'll select Edit rotation and configure your secret to be rotated using your Lambda Function.

 

 

Or, the aws secretsmanager rotate-secret command can be used.

aws secretsmanager rotate-secret \
--secret-id my-secret \
--rotation-lambda-arn <the ARN of your Lambda Function> \
--rotation-rules '{"ScheduleExpression": "cron(0 /4 * * ? *)"}'

 

And now the Rotation Tab should show that your secret is configured to be rotated. Nice! You can also select Rotate secret immediately to confirm the secret gets rotated, immediately.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f6d3df in the box below so that we can be sure you are a human.