connect to secrets manager in python

To connect to AWS Secrets Manager in Python, you will first need to install the AWS SDK for Python (Boto3) using pip:

main.py
pip install boto3
18 chars
2 lines

Then, you can use the following code snippet to connect to AWS Secrets Manager and retrieve a secret value:

main.py
import boto3
from botocore.exceptions import ClientError

def get_secret():

    secret_name = "my-secret-name"
    region_name = "us-west-2"

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )

    # Get the value of the secret
    try:
        get_secret_value_response = client.get_secret_value(SecretId=secret_name)
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print("The requested secret " + secret_name + " was not found")
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            print("The request was invalid due to:", e)
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            print("The request had invalid params:", 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:
            secret = get_secret_value_response['SecretBinary']

        return secret
1272 chars
35 lines

Note that in order to authenticate with AWS and access the secret stored in AWS Secrets Manager, you will need to provide valid AWS credentials either through environment variables or via a credentials file in your home directory.

gistlibby LogSnag