Introduction

As we've learned in our previous lessons, AWS Secrets Manager is a powerful service that helps protect access to your applications, services, and IT resources. It allows you to easily rotate, manage, and retrieve database credentials, API keys, and other secrets throughout their lifecycle. In this lesson, we're going to explore the advanced features of AWS Secrets Manager with Python's AWS SDK, Boto3.

Generating a Random Password

One way to ensure that passwords are strong and secure is to generate a random password using AWS Secrets Manager. Let's see how we can accomplish this:

import boto3

# Initialize the Secrets Manager client
client = boto3.client('secretsmanager')

# Generate a simple random password
response_simple = client.get_random_password()
print("Simple Random Password:", response_simple['RandomPassword'])

# Generate a complex random password including special characters and without any ambiguous characters
response_complex = client.get_random_password(
  PasswordLength=20,                  # Specify length
  IncludeSpace=True,                  # Include space character
  RequireEachIncludedType=True,       # Require at least one character from each included type
  ExcludeCharacters="/@\" "           # Exclude specific characters
)
print("Complex Random Password:", response_complex['RandomPassword'])

In this piece of code, we first create a client with AWS Secrets Manager using the boto3.client('secretsmanager') call. Then, we called the get_random_password() function, which generates a random password. The function accepts numerous parameters for customization, such as PasswordLength, ExcludeCharacters, ExcludeNumbers, ExcludePunctuation, ExcludeUppercase, ExcludeLowercase, IncludeSpace, RequireEachIncludedType.

Listing All Secrets

AWS Secrets Manager provides a function to list all the secrets that are stored in it. The list_secrets() function returns a list of all secret information:

# List all secrets
response = client.list_secrets()

# Print each secret name
for secret in response['SecretList']:
    print("Secret Name:", secret['Name'])
Tagging and Untagging Secrets

Tagging secrets can help with categorizing and managing secrets. The tag_resource() function is used to add tags to a secret. To remove tags, the untag_resource() function is used.

# Add tags to a secret
response = client.tag_resource(
    SecretId='MyTestSecretId',
    Tags=[
        {
            'Key': 'Environment',
            'Value': 'Production'
        },
    ]
)

# Remove tags from a secret
response = client.untag_resource(
    SecretId='MyTestSecretId',
    TagKeys=[
        'Environment',
    ]
)
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal