manager

Manage the underlying boto3 session and client.

class boto_session_manager.manager.BotoSesManager(aws_access_key_id: str | None = NOTHING, aws_secret_access_key: str | None = NOTHING, aws_session_token: str | None = NOTHING, region_name: str | None = NOTHING, botocore_session: botocore.session.Session | None = NOTHING, profile_name: str = NOTHING, default_client_kwargs: dict = NOTHING, expiration_time: datetime = NOTHING)[source]

Boto3 session and client manager that use cache to create low level client.

Note

boto3.session.Session is a static object that won’t talk to AWS endpoint. also session.client(“s3”) won’t talk to AWS endpoint right away. The authentication only happen when a concrete API request called.

create_boto_ses() boto3.session.Session[source]

Create a new boto3 session object from the BotoSesManager.

property boto_ses: boto3.session.Session

Get boto3 session from metadata. This is a cached property.

property aws_account_user_id: str

Get current aws account user id of the boto session. This is a cached property.

property masked_aws_account_user_id: str

Get the masked current aws account user id of the boto session.

property aws_account_id: str

Get current aws account id of the boto session. This is a cached property.

property masked_aws_account_id: str

Get the masked current aws account id of the boto session.

property principal_arn: str

Get current principal arn of the boto session. This is a cached property.

property masked_principal_arn: str

Get the masked principal arn of the boto session.

property aws_region: str

Get current aws region of the boto session. This is a cached property.

property aws_account_alias: str | None

Get the first aws account alias of the boto session. This is a cached property.

print_who_am_i(masked: bool = True)[source]

Print the boto session AWS Account and IAM principal information.

get_client(service_name: str, region_name: str = NOTHING, api_version: str = NOTHING, use_ssl: bool = True, verify: bool | str = NOTHING, endpoint_url: str = NOTHING, aws_access_key_id: str = NOTHING, aws_secret_access_key: str = NOTHING, aws_session_token: str = NOTHING, config=NOTHING) BaseClient[source]

Get aws boto client using cache.

get_resource(service_name: str, region_name: str = NOTHING, api_version: str = NOTHING, use_ssl: bool = True, verify: bool | str = NOTHING, endpoint_url: str = NOTHING, aws_access_key_id: str = NOTHING, aws_secret_access_key: str = NOTHING, aws_session_token: str = NOTHING, config=NOTHING) ServiceResource[source]

Get aws boto service resource using cache.

assume_role(role_arn: str, role_session_name: str = NOTHING, duration_seconds: int = 3600, tags: list[dict[str, str]] | None = NOTHING, transitive_tag_keys: list[str] | None = NOTHING, external_id: str = NOTHING, mfa_serial_number: str = NOTHING, mfa_token: str = NOTHING, source_identity: str = NOTHING, region_name: str = NOTHING, auto_refresh: bool = False) BotoSesManager[source]

Assume an IAM role, create another BotoSesManager and return.

Parameters:

auto_refresh – if True, the assumed role will be refreshed automatically. Note: this uses AssumeRoleCredentialFetcher and DeferredRefreshableCredentials from botocore, which are not public API officially supported by botocore.

is_expired(delta: int = 0) bool[source]

Check if this boto session is expired.

awscli()[source]

Temporarily set up environment variables to pass the boto session credential to AWS CLI. On exit the original environment is restored.

Example:

import subprocess

bsm = BotoSesManager(...)

with bsm.awscli():
    subprocess.run(["aws", "sts", "get-caller-identity"])

Reference:

to_snapshot() dict[source]

Serialize the current session credentials (access key, secret key, optional session token, region) into a plain dict that can be persisted to disk with temp_snapshot() and later restored with from_snapshot() or from_snapshot_file().

classmethod from_snapshot(snapshot: dict)[source]

Create a BotoSesManager from a snapshot dict previously produced by to_snapshot().

classmethod from_snapshot_file(path: str | Path | None = PosixPath('/home/docs/.bsm-snapshot.json'))[source]

Read a JSON snapshot file from path (default ~/.bsm-snapshot.json) and reconstruct a BotoSesManager. Pair this with temp_snapshot() to hand credentials across process boundaries.

temp_snapshot(path: str | Path | None = PosixPath('/home/docs/.bsm-snapshot.json'))[source]

Context manager that writes the current credentials to a JSON file (default ~/.bsm-snapshot.json) and deletes it on exit.

Why this exists: when you use awscli() to switch the environment to a different AWS account, child processes (scripts, CLI tools) lose access to the original session. By saving a snapshot first, those child processes can call from_snapshot_file() to recover the original credentials.

Example:

import subprocess

bsm_default = BotoSesManager()
bsm_acc_b = BotoSesManager(profile_name="acc_b")
with bsm_default.temp_snapshot():
    with bsm_acc_b.awscli():
        # env now points to account B
        subprocess.run(["aws", "sts", "get-caller-identity"])
        # my_script.py can call BotoSesManager.from_snapshot_file()
        # to get the original (account A) session back
        subprocess.run(["python", "my_script.py"])
clear_cache()[source]

Clear all the boto session and boto client cache.