AWS Assume Role Lib
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
- breaking Starting with v2.8, the library introduced 'compatibility version 2', indicating potential breaking changes. Specifically, the behavior of `region_name=None` for child sessions was changed to link to the parent session's region rather than copying it, which can affect implicit region resolution.
- breaking In v2.9, the logic for generating `RoleSessionName` when `SourceIdentity` is provided was updated. If `RoleSessionName` is not explicitly set but `SourceIdentity` is, `SourceIdentity` will be used for `RoleSessionName`. This differs from pre-v2.8 behavior where a `botocore`-generated value was always used.
- gotcha `assume_role()` performs parameter validation by default, which adds a small time penalty. This validation helps catch issues before the child session is first used, as `boto3` defers credential retrieval.
- gotcha The `assume_role()` function in `aws-assume-role-lib` offers enhanced parameter types compared to the raw `boto3 sts.AssumeRole` API. Specifically, `Policy` can be a Python dictionary (instead of a JSON string), `PolicyArns` can be a list of strings (instead of a list of dicts), and `DurationSeconds` can be a `datetime.timedelta` object (instead of an integer).
- gotcha Direct usage of `boto3.client('sts').assume_role()` requires manual handling of credential expiration and refreshing, and explicit provision of a `RoleSessionName`. `aws-assume-role-lib` abstracts these complexities.
Install
-
pip install aws-assume-role-lib
Imports
- assume_role
from aws_assume_role_lib import assume_role
- generate_lambda_session_name
from aws_assume_role_lib import generate_lambda_session_name
Quickstart
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}")