skip to Main Content

I want to retrieve AWS secrets using python boto3 and I came across this sample code:

But it is confusing. I don’t see boto3 library import in the python file. Not an expert of Python, so any help in understanding this much appreciated.

I was expecting to have the AWS secrets name and boto3 libarary as part of the python function.

2

Answers


  1. Per the documentation, each of the example folders has one or more main runner scripts.

    For the Secrets Manager examples, you would run either:

    1. python scenario_get_secret.py, or
    2. python scenario_get_batch_secrets.py

    Each of these ‘runner’ scripts imports the relevant Python code e.g. get_secret_value.py.

    The code is structured this way so that you can easily test the code while separating the test code from the reusable utility code (that you would potentially use).

    Login or Signup to reply.
  2. To work with AWS Secrets Manager using the boto3 library in Python, you indeed need to import the boto3 library first. Additionally, to retrieve a secret, you need to know the name or the ARN (Amazon Resource Name) of the secret you wish to retrieve.

    Here’s a simple, complete example that demonstrates how to import the boto3 library and retrieve a secret from AWS Secrets Manager. This example assumes you have already set up your AWS credentials in a way that boto3 can automatically detect them (for example, by using the AWS CLI and running aws configure).

    import boto3
    from botocore.exceptions import ClientError
    
    def get_secret(secret_name):
        # Create a Secrets Manager client
        client = boto3.client('secretsmanager')
    
        try:
            # Attempt to retrieve the secret value
            get_secret_value_response = client.get_secret_value(SecretId=secret_name)
        except ClientError as e:
            # Handle the exception if the secret can't be retrieved
            raise e
    
        # If there's no exception, process the retrieved secret
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            # For binary secrets, decode them before using
            secret = get_secret_value_response['SecretBinary'].decode('utf-8')
        return secret
    
    # Example usage
    secret_name = 'your_secret_name_here'
    secret_value = get_secret(secret_name)
    print(secret_value)
    

    I hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search