Search code examples
pythonamazon-web-servicesaws-lambdaaws-secrets-manager

Retrieve secrets from AWS Secrets Manager in a Lambda function


I have been trying to use Secret Manager in the lambda function in AWS.

I am using Secret Manager to store my Redshift credentials and want to use the sample code given by the AWS Secret manager to retrieve the secret via the lambda function.

I have set up a Secret in secret manager which contains my redshift credentials (username, password)

I am trying to set up a lambda function which would get the secrets from Secret Manger: below is the sample code:


import boto3
import base64
from botocore.exceptions import ClientError


def lambda_handler(event, context):
    
    def get_secret():
        secret_name = "test/MySecret"
        region_name = "eu-west-2"

    # 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:
        if e.response['Error']['Code'] == 'DecryptionFailureException':
            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        # Decrypts secret using the associated KMS CMK.
        # Depending on whether the secret is a string or binary, one of these fields will be populated.
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])

I am getting the following errors whilst running the lambda function:

{
  "errorMessage": "name 'secret_name' is not defined",
  "errorType": "NameError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 22, in lambda_handler\n    SecretId = secret_name\n"
  ]
}

I have defined the secret_name at the start of the lambda function but I am getting the secret_name' is not defined error. Any suggestions how i can fix the issue


Solution

  • So the thing is python cannot get the value of secret_name variable, the reason is it is under a function

    def get_secret():
        secret_name = "test/MySecret"
        region_name = "eu-west-2"
    

    So instead if you just use secret_name = "test/MySecret" without the function part, the sample code should work