How to use Boto3 to generate a random password in AWS Secret Manager

Problem Statement: Use boto3 library in Python to generate a random password in AWS Secrets Manager

AWS Secrets Manager provides a get_random_password API that generates cryptographically secure random passwords. This is useful for creating strong passwords for database users, applications, or other AWS services.

Prerequisites

Before using this functionality, ensure you have:

  • AWS credentials configured (via AWS CLI, IAM roles, or environment variables)

  • Proper IAM permissions for secretsmanager:GetRandomPassword

  • boto3 library installed: pip install boto3

Algorithm Steps

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: Create an AWS session using boto3. Ensure region_name is configured in your AWS profile.

  • Step 3: Create an AWS client for secretsmanager service.

  • Step 4: Call get_random_password with desired password complexity parameters.

  • Step 5: Extract the generated password from the response.

  • Step 6: Handle exceptions for robust error management.

Basic Example

Here's a simple example to generate a random password ?

import boto3
from botocore.exceptions import ClientError

def generate_random_password():
    session = boto3.session.Session()
    client = session.client('secretsmanager')
    
    try:
        response = client.get_random_password(
            PasswordLength=16,
            ExcludeNumbers=False,
            ExcludePunctuation=True,
            ExcludeUppercase=False,
            ExcludeLowercase=False,
            IncludeSpace=False,
            RequireEachIncludedType=True
        )
        return response['RandomPassword']
    except ClientError as e:
        raise Exception(f"AWS client error: {e}")
    except Exception as e:
        raise Exception(f"Unexpected error: {e}")

# Generate password
password = generate_random_password()
print(f"Generated password: {password}")
Generated password: mKpL8nQwXz2YvBcR

Advanced Example with Custom Parameters

You can customize password generation with specific requirements ?

import boto3
from botocore.exceptions import ClientError

def generate_custom_password(length=20, exclude_chars=""):
    client = boto3.client('secretsmanager', region_name='us-east-1')
    
    try:
        response = client.get_random_password(
            PasswordLength=length,
            ExcludeCharacters=exclude_chars,
            ExcludeNumbers=False,
            ExcludePunctuation=False,
            ExcludeUppercase=False,
            ExcludeLowercase=False,
            IncludeSpace=False,
            RequireEachIncludedType=True
        )
        
        return {
            'password': response['RandomPassword'],
            'length': len(response['RandomPassword'])
        }
    except ClientError as e:
        print(f"Error generating password: {e}")
        return None

# Generate different types of passwords
simple_password = generate_custom_password(12, exclude_chars="!@#$%^&*()")
complex_password = generate_custom_password(24)

print(f"Simple password (12 chars, no special): {simple_password['password']}")
print(f"Complex password (24 chars): {complex_password['password']}")
Simple password (12 chars, no special): mKpL8nQwXz2Y
Complex password (24 chars): mKpL8n!QwXz2Y@vBcR#$%asd

Parameter Options

Parameter Type Description Default
PasswordLength Integer Length of password (6-4096) 32
ExcludeCharacters String Characters to exclude ""
ExcludeNumbers Boolean Exclude numbers (0-9) False
ExcludePunctuation Boolean Exclude special characters False
RequireEachIncludedType Boolean Include at least one of each type True

Error Handling Best Practices

import boto3
from botocore.exceptions import ClientError, NoCredentialsError

def robust_password_generator():
    try:
        client = boto3.client('secretsmanager')
        response = client.get_random_password(PasswordLength=16)
        return response['RandomPassword']
    
    except NoCredentialsError:
        print("Error: AWS credentials not found")
        return None
    except ClientError as e:
        error_code = e.response['Error']['Code']
        if error_code == 'InvalidParameterException':
            print("Error: Invalid parameters provided")
        else:
            print(f"AWS error: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

Conclusion

AWS Secrets Manager's get_random_password API provides a secure way to generate cryptographically strong passwords. Use appropriate parameter combinations based on your security requirements and always implement proper error handling for production applications.

---
Updated on: 2026-03-25T19:03:04+05:30

679 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements