Boto Session Manager

1.8.1 · active · verified Sun Apr 12

boto_session_manager is a lightweight Python library designed to simplify the management of AWS boto3 sessions within application code. It enhances the native boto3 SDK by providing features such as boto3 Client auto-completion, cached boto3 Clients, in-application IAM role assumption, and temporary credential management for the AWS CLI. It aims to provide a more user-friendly development experience with boto3. It is currently at version 1.8.1 and actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the BotoSesManager, retrieve a cached boto3 client for a service (e.g., S3), and perform a basic operation. It also includes an example of assuming an IAM role, which is a key feature of the library, assuming a valid role ARN is provided via an environment variable or hardcoded for testing.

from boto_session_manager import BotoSesManager

# Initialize the session manager (uses default AWS credentials chain)
bsm = BotoSesManager()

# Get an S3 client. Clients are cached for reuse.
s3_client = bsm.get_client("s3")

# Alternatively, use attribute access for common services for auto-complete
# s3_client = bsm.s3_client

# Example: List S3 buckets
try:
    response = s3_client.list_buckets()
    print("S3 Buckets:")
    for bucket in response.get("Buckets", []):
        print(f"- {bucket['Name']}")
except Exception as e:
    print(f"Error listing buckets: {e}")

# Example: Assuming an IAM role
# This assumes 'MY_ASSUME_ROLE_ARN' environment variable is set
# or replaced with a valid ARN.
assume_role_arn = os.environ.get('MY_ASSUME_ROLE_ARN', 'arn:aws:iam::123456789012:role/MyTestRole')
if '123456789012' not in assume_role_arn: # Simple check to avoid running with dummy ARN
    try:
        print(f"\nAttempting to assume role: {assume_role_arn}")
        assumed_bsm = bsm.assume_role(
            RoleArn=assume_role_arn,
            RoleSessionName="my-assumed-session"
        )
        ec2_client_assumed = assumed_bsm.get_client("ec2")
        print(f"Successfully obtained EC2 client with assumed role: {ec2_client_assumed}")
    except Exception as e:
        print(f"Error assuming role: {e}")

view raw JSON →