Skip to content

Instantly share code, notes, and snippets.

@wvxavier
Last active August 24, 2020 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wvxavier/d6110973c75fc1faeee53069f7d1aa8c to your computer and use it in GitHub Desktop.
Save wvxavier/d6110973c75fc1faeee53069f7d1aa8c to your computer and use it in GitHub Desktop.
secret_rotation_handler
def lambda_handler(event, context):
# Current Secret via SSM
current_secret = get_current_secret('/rds/PASSWORD')
# Connect to RDS using current secret
conn = get_connection(current_secret)
# Generates new random secret
new_secret = generate_secret()
# Connects to RDS and rotate secret
rotate_secret(conn, new_secret, current_secret)
# IMPORT! checks if the new secret is valid before update any SSM parameter
test_result = get_connection(new_secret)
# If new secret succefully connects to RDS then update SSM for application
if test_result != None:
logger.info('Secret successfully rotated')
update_parameter_ssm('/rds/PASSWORD', new_secret)
database_url = build_db_url(new_secret)
update_parameter_ssm('/rds/DATABASE_URL', database_url)
# Restart application container
restart_tasks()
else:
# If new secret is invalid SSM parameters remains current secret
logger.info('Secret NOT rotated, SSM parameters not updated')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment