AWS Assume Role Lib

2.10.0 · active · verified Tue Apr 14

aws-assume-role-lib simplifies assumed role session chaining with automatic credential refreshing for boto3. As of version 2.10.0, released May 14, 2022, it provides an abstraction layer over `sts.AssumeRole` to handle credential expiration and session name generation, common in serverless environments like AWS Lambda. The library maintains a steady release cadence, with updates addressing new boto3 features and CLI support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a parent `boto3` session and then use `aws_assume_role_lib.assume_role` to get a new session with assumed role credentials. The assumed session automatically handles credential refreshing. Ensure the `ROLE_ARN` environment variable is set or replace the placeholder.

import os
import boto3
from aws_assume_role_lib import assume_role

# Set your target role ARN here, e.g., from an environment variable
# Ensure the calling principal has 'sts:AssumeRole' permission on this ARN.
ROLE_ARN = os.environ.get('AWS_ASSUME_ROLE_LIB_ROLE_ARN', 'arn:aws:iam::123456789012:role/MyTestRole')

if ROLE_ARN == 'arn:aws:iam::123456789012:role/MyTestRole':
    print("WARNING: Using a placeholder ROLE_ARN. Please set AWS_ASSUME_ROLE_LIB_ROLE_ARN environment variable or replace in code.")

# Create a parent boto3 session (e.g., from default credentials or a profile)
parent_session = boto3.Session()

try:
    # Assume the role using aws-assume-role-lib
    assumed_role_session = assume_role(parent_session, ROLE_ARN)

    # Use the assumed role session to create a client or resource
    sts_client = assumed_role_session.client('sts')
    caller_identity = sts_client.get_caller_identity()
    print(f"Successfully assumed role. Caller ARN: {caller_identity['Arn']}")

    # Example: Use the assumed role session to list S3 buckets
    # s3_client = assumed_role_session.client('s3')
    # buckets = s3_client.list_buckets()
    # print(f"Buckets: {[b['Name'] for b in buckets['Buckets']]}")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →