### Installation of aws-assume-role-lib Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Provides instructions for installing the `aws-assume-role-lib` package using pip or by directly adding the Python script to a project. The pip installation is recommended for managing dependencies. ```bash pip install --user aws-assume-role-lib ``` -------------------------------- ### Basic Usage of aws-assume-role-lib Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Demonstrates the fundamental usage of the `aws-assume-role-lib` library. It shows how to import the `assume_role` function, create a boto3 session (optionally with a profile), and then use `assume_role` to get a new session with assumed credentials. It also shows how to use both the original and assumed role sessions. ```python import boto3 from aws_assume_role_lib import assume_role # Get a session session = boto3.Session() # or with a profile: # session = boto3.Session(profile_name="my-profile") # Assume the session assumed_role_session = assume_role(session, "arn:aws:iam::123456789012:role/MyRole") # do stuff with the original credentials print(session.client("sts").get_caller_identity()["Arn"]) # do stuff with the assumed role print(assumed_role_session.client("sts").get_caller_identity()["Arn"]) ``` -------------------------------- ### Python: Reusing Sessions Between Invocations (Manual Caching) Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/lambda-demo/README.md This example demonstrates an attempt to improve performance by moving role assumption outside the handler to leverage long-lived Lambda instances. It highlights the potential issue of credential expiration and the need for manual caching or refreshing logic if credentials are not managed carefully. ```python import boto3 import os # Assume role during initialization (outside handler) ROLE_ARN = os.environ.get('ASSUMED_ROLE_ARN') SESSION_NAME = 'MyReusableSession' sts_client = boto3.client('sts') assume_role_response = sts_client.assume_role( RoleArn=ROLE_ARN, RoleSessionName=SESSION_NAME ) credentials = assume_role_response['Credentials'] # Create a session with assumed role credentials assumed_role_session = boto3.Session( aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'] ) s3_client = assumed_role_session.client('s3') dynamodb_client = assumed_role_session.client('dynamodb') def handler(event, context): # Potential issue: credentials might expire here before use # Need to check expiration and potentially re-assume role # Use s3_client and dynamodb_client for operations # ... return { 'statusCode': 200, 'body': 'Session initialized outside handler.' } ``` -------------------------------- ### AWS CLI Profile Configuration for Role Assumption Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Demonstrates how to configure AWS CLI profiles for role assumption, which is generally preferred over direct library use for command-line operations. It shows a `source_profile` setup that specifies an existing profile and the role to assume, including optional `role_session_name` and `credential_source` options for alternative credential retrieval methods like environment variables or EC2 instance metadata. ```ini # Example AWS CLI config file (~/.aws/config) # This is a pre-existing profile you already have (e.g., IAM User, AWS SSO) [profile profile-to-call-assume-role-with] # source_profile = existing_profile_name # credential_type = aws_sso or access_key_id etc. # Profile for the assumed role [profile my-assumed-role] role_arn = arn:aws:iam::123456789012:role/MyRole # optional: role_session_name = MyRoleSessionName source_profile = profile-to-call-assume-role-with # or instead of source_profile, you can tell it to use external credentials: # credential_source = Environment # credential_source = Ec2InstanceMetadata ``` -------------------------------- ### Python: Using aws-assume-role-lib for Transparent Credential Management Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/lambda-demo/README.md This snippet illustrates the use of the aws-assume-role-lib library to simplify role assumption. The library automatically handles caching and refreshing of credentials, allowing the assumed role session to be created during initialization and remain valid for the life of the Lambda instance. It also demonstrates generating a session name using aws_assume_role_lib.generate_lambda_session_name(). ```python import boto3 import os import aws_assume_role_lib # Define Role ARN and generate a session name ROLE_ARN = os.environ.get('ASSUMED_ROLE_ARN') # Generate a session name suitable for RoleSessionName or SourceIdentity # Includes function name, version, and instance identifier for traceability session_name = aws_assume_role_lib.generate_lambda_session_name() # Assume role during initialization using the library assumed_role_session = aws_assume_role_lib.assume_role( ROLE_ARN, RoleSessionName=session_name ) # Create clients from the transparently managed assumed role session s3_client = assumed_role_session.client('s3') dynamodb_client = assumed_role_session.client('dynamodb') def handler(event, context): # The assumed_role_session handles credential refresh transparently # Use s3_client and dynamodb_client for operations # ... return { 'statusCode': 200, 'body': 'aws-assume-role-lib used for transparent role assumption.' } ``` -------------------------------- ### Verbose boto3 AssumeRole Without Library Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Demonstrates the traditional, verbose method of assuming an AWS role using boto3. This approach requires manually calling `sts.AssumeRole`, creating a new boto3 session with the returned credentials, and explicitly managing credential expiration and refreshing. It is prone to boilerplate code. ```python role_arn = "arn:aws:iam::123456789012:role/MyRole" session = boto3.Session() sts = session.client("sts") response = sts.assume_role( RoleArn=role_arn, RoleSessionName="something_you_have_to_think_about" ) credentials = response["Credentials"] assumed_role_session = boto3.Session( aws_access_key_id=credentials["AccessKeyId"], aws_secret_access_key=credentials["SecretAccessKey"], aws_session_token=credentials["SessionToken"] ) # use the session print(assumed_role_session.client("sts").get_caller_identity()) ``` -------------------------------- ### Patching Boto3 for Assume Role (Python) Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Demonstrates how to patch the boto3 library to make the `assume_role` functionality directly available. This enables calling `boto3.assume_role()` or `boto3.Session.assume_role()` for a more streamlined AWS role assumption process. ```python import boto3 import aws_assume_role_lib aws_assume_role_lib.patch_boto3() assumed_role_session = boto3.assume_role("arn:aws:iam::123456789012:role/MyRole") # the above is basically equivalent to: # aws_assume_role_lib.assume_role(boto3.Session(), "arn:aws:iam::123456789012:role/MyRole") session = boto3.Session(profile_name="my-profile") assumed_role_session = session.assume_role("arn:aws:iam::123456789012:role/MyRole") ``` -------------------------------- ### Simplified AssumeRole with aws-assume-role-lib Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Illustrates the concise usage of the `aws-assume-role-lib` to assume an AWS role. This method collapses the previous verbose code into a single function call, `aws_assume_role_lib.assume_role`, which handles credential refreshing and role session name generation automatically. ```python role_arn = "arn:aws:iam::123456789012:role/MyRole" session = boto3.Session() assumed_role_session = aws_assume_role_lib.assume_role(session, role_arn) # use the session print(assumed_role_session.client("sts").get_caller_identity()) ``` -------------------------------- ### Format AWS Role ARNs Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Provides utility functions for formatting AWS IAM Role ARNs and assumed role session ARNs. `get_role_arn` constructs a role ARN from account ID, role name, and an optional path and partition. `get_assumed_role_session_arn` formats the ARN for an assumed role session, requiring account ID, role name, session name, and an optional partition. ```python from typing import Union def get_role_arn( account_id: Union[str, int], role_name: str, path: str = "", partition: str = "aws", ) -> str: """Constructs an IAM role ARN. Args: account_id: The AWS account ID. role_name: The name of the role. path: Optional path for the role (e.g., '/my/path/'). partition: The AWS partition (default is 'aws'). Returns: The formatted IAM role ARN. """ # ... implementation details ... pass def get_assumed_role_session_arn( account_id: Union[str, int], role_name: str, role_session_name: str, partition: str = "aws", ) -> str: """Formats an assumed role session ARN. Args: account_id: The AWS account ID. role_name: The name of the role being assumed. role_session_name: The name of the session. partition: The AWS partition (default is 'aws'). Returns: The formatted assumed role session ARN. """ # ... implementation details ... pass ``` -------------------------------- ### Error Handling with aws-error-utils in Python Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/lambda-demo/README.md This snippet demonstrates how to use the aws-error-utils library to simplify exception handling for AWS API calls. It replaces verbose try-except blocks for specific AWS errors like AccessDenied with more concise checks. This approach improves code readability and maintainability. ```python from aws_error_utils import errors # ... assuming s3 client and constants BUCKET_NAME, KEY are defined ... s3_result = "" try: response = s3.get_object( Bucket=BUCKET_NAME, Key=KEY, ) s3_result = response['Body'].read() except errors.AccessDenied: s3_result = "Access denied!" except Exception as e: s3_result = str(e) ``` -------------------------------- ### Naive Role Assumption in Lambda (Python) Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/lambda-demo/README.md Illustrates a basic approach to assuming an AWS role within a Lambda function. This method involves creating an STS client and explicitly calling AssumeRole on each invocation, then using the returned temporary credentials to instantiate service clients. It requires setting RoleSessionName and optionally SourceIdentity. ```python import boto3 def lambda_handler(event, context): # ... other setup ... sts_client = boto3.client('sts') # Assume role assumed_role_object = sts_client.assume_role( RoleArn=ROLE_ARN, RoleSessionName='MySessionName', SourceIdentity='MySourceIdentity' ) # Create clients with assumed role credentials s3_client = boto3.client( 's3', aws_access_key_id=assumed_role_object['Credentials']['AccessKeyId'], aws_secret_access_key=assumed_role_object['Credentials']['SecretAccessKey'], aws_session_token=assumed_role_object['Credentials']['SessionToken'] ) dynamodb_client = boto3.client( 'dynamodb', aws_access_key_id=assumed_role_object['Credentials']['AccessKeyId'], aws_secret_access_key=assumed_role_object['Credentials']['SecretAccessKey'], aws_session_token=assumed_role_object['Credentials']['SessionToken'] ) # ... use s3_client and dynamodb_client ... return { 'statusCode': 200, # ... results ... } ``` -------------------------------- ### Python: AssumeRole with Boto3 Sessions Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/lambda-demo/README.md This snippet shows how to use boto3 Sessions to assume an IAM role within a Lambda handler. It creates a default session, then an STS client to call AssumeRole. The returned credentials are used to create a new session for S3 and DynamoDB clients. This approach calls AssumeRole on every invocation. ```python import boto3 def handler(event, context): # Create a default session using Lambda function's credentials session = boto3.Session() sts_client = session.client('sts') # Assume the role response = sts_client.assume_role( RoleArn='arn:aws:iam::123456789012:role/YourAssumedRole', RoleSessionName='MySessionName' ) # Get credentials from the response credentials = response['Credentials'] # Create a new session with the assumed role credentials assumed_role_session = boto3.Session( aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'] ) # Create clients from the assumed role session s3_client = assumed_role_session.client('s3') dynamodb_client = assumed_role_session.client('dynamodb') # Use s3_client and dynamodb_client for operations # ... return { 'statusCode': 200, 'body': 'Role assumed and clients created.' } ``` -------------------------------- ### Assume Role Function Interface (Python) Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Defines the signature for the `assume_role` function, detailing required and optional arguments for assuming an AWS role. It supports various parameters for role assumption and session configuration, including options for policy, duration, tags, and region handling. ```python assume_role( # required arguments session: boto3.Session, RoleArn: str, *, # keyword-only arguments for AssumeRole RoleSessionName: str = None, PolicyArns: Union[list[dict[str, str]], list[str]] = None, Policy: Union[str, dict] = None, DurationSeconds: Union[int, datetime.timedelta] = None, Tags: list[dict[str, str]] = None, TransitiveTagKeys: list[str] = None, ExternalId: str = None, SerialNumber: str = None, TokenCode: str = None, SourceIdentity: str = None, additional_kwargs: dict = None, # keyword-only arguments for returned session region_name: Union[str, bool] = None, # keyword-only arguments for assume_role() itself validate: bool = True, cache: dict = None, ) ``` -------------------------------- ### aws-assume-role-lib Usage in AWS Lambda Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Shows how to integrate `aws-assume-role-lib` into an AWS Lambda function for efficient role assumption. By initializing the assumed role session outside the handler, `AssumeRole` API calls are minimized, and the session is reused across invocations within the same execution environment. It also utilizes `generate_lambda_session_name` for dynamic session naming. ```python import os import boto3 from aws_assume_role_lib import assume_role, generate_lambda_session_name # Get the Lambda session SESSION = boto3.Session() # Get the config ROLE_ARN = os.environ["ROLE_ARN"] ROLE_SESSION_NAME = generate_lambda_session_name() # see below for details # Assume the session ASSUMED_ROLE_SESSION = assume_role(SESSION, ROLE_ARN, RoleSessionName=ROLE_SESSION_NAME) def handler(event, context): # do stuff with the Lambda role using SESSION print(SESSION.client("sts").get_caller_identity()["Arn"]) # do stuff with the assumed role using ASSUMED_ROLE_SESSION print(ASSUMED_ROLE_SESSION.client("sts").get_caller_identity()["Arn"]) ``` -------------------------------- ### Cache Assumed Role Credentials Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Implements a file system cache for assumed role credentials using the `JSONFileCache` class. This class creates a specified directory if it doesn't exist and stores credentials in JSON files. It can be passed as a `cache` argument to the `assume_role` function. Any dictionary-like object supporting `__getitem__`, `__setitem__`, and `__contains__` can be used as a cache. ```python from aws_assume_role_lib import assume_role from aws_assume_role_lib.cache import JSONFileCache # Example usage: # assumed_role_session = assume_role( # session, # "arn:aws:iam::123456789012:role/MyRole", # cache=JSONFileCache("path/to/cache/directory") # ) class JSONFileCache: """A cache for assumed role credentials that stores them on the file system. Args: cache_dir: The directory where cache files will be stored. """ def __init__(self, cache_dir: str): # ... implementation details ... pass def __getitem__(self, key: str) -> dict: # ... implementation details ... pass def __setitem__(self, key: str, value: dict) -> None: # ... implementation details ... pass def __contains__(self, key: str) -> bool: # ... implementation details ... pass ``` -------------------------------- ### Generate Lambda Role Session Name Source: https://github.com/benkehoe/aws-assume-role-lib/blob/main/README.md Generates a role session name for AWS Lambda functions, incorporating function name, version, and a unique identifier for improved traceability. The name is truncated to comply with the 64-character limit, prioritizing function name and identifier. It extracts context from environment variables but allows overrides. ```python def generate_lambda_session_name(): """Generates a role session name for Lambda functions. The session name is derived from the function name, version (if not '$LATEST'), and a unique identifier from the CloudWatch log stream name or a timestamp. It adheres to the 64-character limit, truncating as necessary. """ # ... implementation details ... pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.