boto3-assume

0.2.1 · active · verified Fri Apr 17

boto3-assume is a Python library that simplifies creating boto3 assume role sessions with automatic credential refreshing. It provides a convenient API for managing temporary AWS credentials via IAM roles. The library is actively maintained with frequent, small releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `boto3-assume.assume_role` to obtain a boto3 session with temporary credentials from an assumed IAM role, and then use that session to interact with an AWS service like S3. Ensure your environment has AWS credentials configured (e.g., `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, or `AWS_PROFILE`) and replace the placeholder `role_arn`.

import boto3_assume
import boto3
import os

# Replace with your actual role ARN and session name
# For local testing, ensure your AWS credentials are configured (e.g., via ~/.aws/credentials or environment variables)
role_arn = os.environ.get('AWS_ASSUME_ROLE_ARN', 'arn:aws:iam::123456789012:role/MyTestRole')
role_session_name = os.environ.get('AWS_ASSUME_SESSION_NAME', 'Boto3AssumeQuickstartSession')

if not role_arn.startswith('arn:aws:iam::'):
    print("Warning: AWS_ASSUME_ROLE_ARN not set or invalid. Using a placeholder ARN. This example will likely fail unless configured correctly.")

try:
    # Assume the role and get a boto3 session object
    assumed_session = boto3_assume.assume_role(
        role_arn=role_arn,
        role_session_name=role_session_name
    )

    # Use the assumed session to create a client (e.g., S3)
    s3_client = assumed_session.client('s3')
    print(f"Successfully assumed role '{role_arn}' with session name '{role_session_name}'.")

    # Example: List S3 buckets using the assumed role
    print("Attempting to list S3 buckets...")
    buckets_response = s3_client.list_buckets()
    bucket_names = [b['Name'] for b in buckets_response.get('Buckets', [])]
    print(f"Found {len(bucket_names)} S3 buckets: {bucket_names[:3]}...")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your AWS credentials are configured and the role ARN is correct and accessible.")

view raw JSON →