Skip to content

Instantly share code, notes, and snippets.

@Harrisonkamau
Last active October 31, 2019 08:47
Show Gist options
  • Save Harrisonkamau/d65f5f732e2714d2c4816280a73f4084 to your computer and use it in GitHub Desktop.
Save Harrisonkamau/d65f5f732e2714d2c4816280a73f4084 to your computer and use it in GitHub Desktop.
AWS Secrets Rotation using Node.js (aws-sdk)
// Ensure you have installed these two packages
const AWS = require('aws-sdk');
const config = require('config');
// this assumes that you have a config folder at the root of the project
// check more about node-config here:
// https://github.com/lorenwest/node-config
// if you're not using `config`, then the values from the .env file as shown below
// check sample config files contained in the config folder
const endpoint = config.get('AWS.endpoint');
const region = config.get('AWS.region');
const secretName = config.get('AWS.secretName');
const clientToken = config.get('AWS.clientToken');
const rotationInterval = Number(config.get('AWS.rotation.interval')); // ensure this is an Integer
const rotationLambdaARN = config.get('AWS.rotation.lambdaARN')
const secretsManager = new AWS.SecretsManager({
endpoint,
region,
});
const params = {
SecretId: secretName,
ClientRequestToken: clientToken,
RotationLamdaARN: rotationLambdaARN,
RotationRules: {
AutomaticallyAfterDays: rotationInterval,
},
};
exports.handler = async (event, context) => {
try {
const response = await secretsManager.rotateSecret(params).promise();
console.log(`${secretName} secret rotation complete`);
console.log(response);
} catch (error) {
console.error(`An error occurred while attempting to rotate ${secretName} secret`);
console.log(error);
}
};
// SAMPLE ENVIRONMENT/CONFIG FILES- Use what fits your current app setup
/**
* Sample config folder
* this assumes you're using ES5
*/
// config/default.js
// REPLACE THE FOLLOWING WITH THE CORRECT VALUES!
module.exports = {
AWS: {
endpoint: 'your endpoint',
region: 'us-west-2',
secretName: 'DatabaseSecret',
clientToken: 'token',
rotation: {
interval: 30,
lambdaARN: 'arn:aws:lambda:us-west-2:123456789012:function:MyTestDatabaseRotationLambda'
}
},
};
/**
* If you're reading values from the .env file
*/
const {
AWS_ENDPOINT,
AWS_REGION,
AWS_SECRET_NAME,
AWS_CLIENT_TOKEN,
AWS_SECRET_ROTATION_INTERVAL,
} = process.env;
// resources
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#rotateSecret-property
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment