Best Python code snippet using localstack_python
lambda_rotate_secret.py
Source:lambda_rotate_secret.py
...12 return f"lambda_rotate_secret_rotation_{version_id}"13# Returns the SecretId used when signalling that a ResourceNotFoundException was received when14# requesting the secret value for a pending secret version during create_secret stage.15# The version_id given represents the version_id of the current secret value after rotation.16def secret_signal_resource_not_found_exception_on_create(version_id: str) -> str:17 return f"ResourceNotFoundException_{version_id}"18def handler(event, context):19 """Secrets Manager Rotation Template20 This is a template for creating an AWS Secrets Manager rotation lambda21 Args:22 event (dict): Lambda dictionary of event parameters. These keys must include the following:23 - SecretId: The secret ARN or identifier24 - ClientRequestToken: The ClientRequestToken of the secret version25 - Step: The rotation step (one of createSecret, setSecret, testSecret, or finishSecret)26 context (LambdaContext): The Lambda runtime information27 Raises:28 ResourceNotFoundException: If the secret with the specified arn and stage does not exist29 ValueError: If the secret is not properly configured for rotation30 KeyError: If the event parameters do not contain the expected keys31 """32 # Client setup.33 edge_port = os.environ.get("EDGE_PORT") or 456634 protocol = "https" if os.environ.get("USE_SSL") else "http"35 endpoint_url = f"{protocol}://{os.environ['LOCALSTACK_HOSTNAME']}:{edge_port}"36 region = os.environ["AWS_REGION"]37 service_client = boto3.client(38 "secretsmanager", endpoint_url=endpoint_url, verify=False, region_name=region39 )40 arn = event["SecretId"]41 token = event["ClientRequestToken"]42 step = event["Step"]43 # Make sure the version is staged correctly44 metadata = service_client.describe_secret(SecretId=arn)45 if not metadata["RotationEnabled"]:46 logger.error(f"Secret {arn} is not enabled for rotation")47 raise ValueError(f"Secret {arn} is not enabled for rotation")48 #49 versions = metadata["VersionIdsToStages"]50 if token not in versions:51 logger.error(f"Secret version {token} has no stage for rotation of secret {arn}.")52 raise ValueError(f"Secret version {token} has no stage for rotation of secret {arn}.")53 if "AWSCURRENT" in versions[token]:54 logger.info(f"Secret version {token} already set as AWSCURRENT for secret {arn}.")55 return56 elif "AWSPENDING" not in versions[token]:57 logger.error(f"Secret version {token} not set as AWSPENDING for rotation of secret {arn}.")58 raise ValueError(59 f"Secret version {token} not set as AWSPENDING for rotation of secret {arn}."60 )61 if step == "createSecret":62 create_secret(service_client, arn, token)63 elif step == "setSecret":64 set_secret(service_client, arn, token)65 elif step == "testSecret":66 test_secret(service_client, arn, token)67 elif step == "finishSecret":68 finish_secret(service_client, arn, token)69 else:70 raise ValueError("Invalid step parameter")71def create_secret(service_client, arn, token):72 """Create the secret73 This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a74 new secret and put it with the passed in token.75 Args:76 service_client (client): The secrets manager service client77 arn (string): The secret ARN or other identifier78 token (string): The ClientRequestToken associated with the secret version79 Raises:80 ResourceNotFoundException: If the secret with the specified arn and stage does not exist81 """82 # Make sure the current secret exists83 service_client.get_secret_value(SecretId=arn, VersionStage="AWSCURRENT")84 # Now try to get the secret version, if that fails, put a new secret85 try:86 service_client.get_secret_value(SecretId=arn, VersionId=token, VersionStage="AWSPENDING")87 logger.info(f"createSecret: Successfully retrieved secret for {arn}.")88 except service_client.exceptions.ResourceNotFoundException:89 # Signal the correct exception was triggered during create_secret stage.90 sig_exception = secret_signal_resource_not_found_exception_on_create(token)91 service_client.create_secret(Name=sig_exception, SecretString=sig_exception)92 # Generate a random password93 passwd = secret_of_rotation_from_version_id(token)94 # Put the secret95 service_client.put_secret_value(96 SecretId=arn,97 ClientRequestToken=token,98 SecretString=passwd,99 VersionStages=["AWSPENDING"],100 )101 logger.info(102 f"createSecret: Successfully put secret for ARN {arn} and version {token} with passwd {passwd}."103 )104def set_secret(service_client, arn, token):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!