Rotate Secrets
using AWS Lambda
When storing secrets using technologies like AWS Secrets Manager, the rotation of certain secrets, like database credentials, is automated and easy to set up. When it comes to the custom secrets rotation, like the external API keys, the case is not so simple anymore.
In the previous article, we covered the basics of secret rotation including the rationale behind rotation, threats associated with secrets, and the rotation process. If you haven’t read it, check it out right now. Introduction to Secrets Rotation
Rotate custom secrets
Custom secrets stored in Secrets Manager can be rotated using a bespoke AWS Lambda function.
During secret rotation, AWS calls the same Lambda function 4 times, each time with different parameters. The function is executed with the following parameters:
The process consists of 4 steps:
![](http://exlabs.com/wp-content/uploads/2023/01/carbon.png)
Step 1 createSecret – create a new version of the secret
This step is about generating a new secret like password in the lambda code. It will be stored in the Secrets Manager with the AWSPENDING staging label. If you are rotating external API keys, this step consists of making an HTTP request to the API to generate a new API key.Step 2 setSecret – change the credentials in the database or service
If you are rotating external service API keys, you don’t have to do anything here. The API key has already been saved in the external API during the creation HTTP request in Step 1. In the case of generating a secret directly in the Lambda code in the first step, you have to set the generated secret in the database or service here.Step 3 testSecret – Test the new secret version
In this step, you have an opportunity to ensure the new secret works as expected. Rotating external API keys, you should test that you can make successfully call the API using the new key. When rotating database credentials, you can make a test request to the database or service using the generated key.Step 4 finishSecret – Finish the rotation
Up until now, the new secret was saved with the AWSPENDING staging label. This step is about changing the new secret label to AWSCURRENT, and the old secret to AWSPREVIOUS staging label. In the case of generating keys to external API, the process can look as presented below.![4 steps in secrets rotation using AWS Lambda](http://exlabs.com/wp-content/uploads/2023/01/4-steps-secrets-rotation-1.png)