Create lambda function to change Secret Manager- secret
Go to "AWS Secrets Manager" > "Secrets"
Here, the "Secret name" is equivalent for the secret-id and secret value is encrypted by default KMS key -> aws/secretsmanager
Create Lambda function ,save /& deploy
import json
import boto3
from botocore.exceptions import ClientError
import random, string
def getpassword():
secret_name = "backdoorAdmin"
region_name = "us-west-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# For a list of exceptions thrown, see
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
raise e
# Decrypts secret using the associated KMS key.
secret = get_secret_value_response['SecretString']
pwd=json.loads(secret)
return(pwd['mykey'])
def lambda_handler(event,context,getpassword=getpassword):
a=getpassword()
newsecret = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
client = boto3.client('secretsmanager')
secret_name = "backdoorAdmin"
region_name = "us-west-1"
response = client.get_secret_value(SecretId='backdoorAdmin')
secret_value = json.loads(response['SecretString'])
# Update the value of the secret
secret_value['MyKey'] = newsecret
updated_secret_value = json.dumps(secret_value)
# Update the secret in Secrets Manager
response = client.update_secret(
SecretId=secret_name,
SecretString=updated_secret_value
)
if response['HTTPStatusCode']!=200:
return {'statusCode': response['HTTPStatusCode'],'body': json.dumps({'message':'failed to update secret'})}
return {'statusCode': 200,'body': json.dumps({'message': 'Secret rotated successfully.'})}
# sample Response
# {
# "resp": "{'ARN': 'arn:aws:secretsmanager:eu-west-1:56789101212:secret:backdoorAdmin-Z9opme', 'Name': 'backdoorAdmin', 'VersionId': '17839-0a6c-490d-bb1a-ce29f0', 'ResponseMetadata': {'RequestId': '6dc9d5fd-f0aa-4dcb-964d-9033', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '633fd-f0aa-4dcb-964d-9033', 'content-type': 'application/x-amz-json-1.1', 'content-length': '157', 'date': 'Tue, 14 Mar 2023 14:53:14 GMT'}, 'RetryAttempts': 0}}",
# "body": "\"secret updated\""
# }
Create IAM Role with permission SecretsManagerReadWrite and attach it to the lambda function.
Now you need to update your Lambda function's permissions policy to grant access to the secretsmanager.amazonaws.com
principal.
In Secret Manager , Edit rotation configuration for the secret and set the duration(min value is 4hours) and select the lambda fxn.