This script automates the rotation of AWS secret credentials for databases, specifically designed for both MariaDB and MySQL databases with single users. It is based on the original AWS sample scripts but has been modified to meet specific requirements, including:
- Database compatibility: Supports both MariaDB and MySQL.
- Email notifications: Sends updates on rotation success or failure.
-
Secret Versioning:
- AWS Secrets Manager stores credentials in stages:
AWSCURRENT
: Holds the active credentials.AWSPENDING
: Holds a new set of credentials for rotation.AWSPREVIOUS
: Holds the previously rotated credentials.
- AWS Secrets Manager stores credentials in stages:
-
Rotation Trigger:
- Enabling secret autorotation initiates the process:
- A new
AWSPENDING
stage is created. - A Lambda function is triggered with the
createSecret
action.
- A new
- Enabling secret autorotation initiates the process:
-
Secret Creation (Lambda):
- Generates a random password.
- Creates a new secret with the password.
- Assigns the secret to the
AWSPENDING
stage.
-
Secret Setting (Lambda):
- Receives the
setSecret
action. - Uses the
AWSCURRENT
credentials to connect to the database. - The script utilizes the
ALTER USER
command to change the database password. - Updates the database password to the value stored in
AWSPENDING
stage secret.
- Receives the
-
Secret Testing (Lambda):
- Receives the
testSecret
action. - Attempts to connect to the database using the
AWSPENDING
secret. - Sends a failure notification if unsuccessful; otherwise, proceeds.
- Receives the
-
Secret Finalization (Lambda):
- Receives the
finishSecret
action. - Updates the stages:
AWSPENDING
becomesAWSCURRENT
.AWSCURRENT
becomesAWSPREVIOUS
.
- Receives the
The script is organized into three files:
- controller.py: Receives actions from Secrets Manager and forwards them to
core.py
. - core.py: Performs actions using utilities from
library.py
. - library.py: Contains helper functions for database interactions and notifications.
Install required libraries:
pip install -r requirements.txt
- Clone the repository.
- Package the script and its dependencies and Upload the deployment package to AWS Lambda.
- Change the Lambda function's handler to the controller.py function mainHandler().
- Enable secret autorotation on the AWS Secrets Manager console.
- Select the Lambda function you've created as the rotation Lambda function.
- Save your changes and test the secret rotation manually to ensure it's functioning as expected.
This project is licensed under the MIT License.
Caution: Always try the script in a development environment before implementing it in a production environment.
For more detailed information on rotating secrets, refer to the AWS Secrets Manager documentation.