STSRefreshableSession#

class boto3_refresh_session.methods.sts.STSRefreshableSession[source]#

A boto3.session.Session object that automatically refreshes temporary AWS credentials using an IAM role that is assumed via STS.

Parameters:
assume_role_kwargsAssumeRoleConfig | Dict[str, Any]

Required keyword arguments for STS.Client.assume_role (i.e. boto3 STS client). RoleArn is required. RoleSessionName will default to ‘boto3-refresh-session’ if not provided.

For MFA authentication, two modalities are supported:

  1. Dynamic tokens (recommended): Provide SerialNumber in assume_role_kwargs and pass mfa_token_provider callable. The provider callable will be invoked on each refresh to obtain fresh MFA tokens. Do not include TokenCode in this case.

  2. Static/injectable tokens: Provide both SerialNumber and TokenCode in assume_role_kwargs. You are responsible for updating assume_role_kwargs["TokenCode"] before the token expires.

sts_client_kwargsSTSClientConfig | Dict[str, Any], optional

Optional keyword arguments for the STS.Client object. Do not provide values for service_name as they are unnecessary. Default is None.

mfa_token_providerCallable[…, str] | List[str] | str, optional

An optional callable or CLI command or list of command arguments that returns a string representing a fresh MFA token code. If provided, this will be called or run during each credential refresh to obtain a new token, which overrides any TokenCode in assume_role_kwargs. When using this parameter, SerialNumber must be provided in assume_role_kwargs. Callables and lists of command arguments are most recommended. Default is None.

mfa_token_provider_kwargsDict[str, Any], optional

Optional keyword arguments to pass to the mfa_token_provider callable or, when mfa_token_provider is a command string or list of command arguments, these keyword arguments are forwarded to subprocess.run. The stdout, stderr, shell, executable, and preexec_fn parameters are not allowed for security reasons when mfa_token_provider is a command string or list of command arguments forwarded to subprocess.run. Default is None.

defer_refreshbool = True, optional

If True then temporary credentials are not automatically refreshed until they are explicitly needed. If False then temporary credentials refresh immediately upon expiration. It is highly recommended that you use True. Default is True.

advisory_timeoutint = 900, optional

USE THIS ARGUMENT WITH CAUTION!!!

Botocore will attempt to refresh credentials early according to this value (in seconds), but will continue using the existing credentials if refresh fails. Default is 15 minutes (900 seconds).

mandatory_timeoutint = 600, optional

USE THIS ARGUMENT WITH CAUTION!!!

Botocore requires a successful refresh before continuing. If refresh fails in this window (in seconds), API calls may fail. Default is 10 minutes (600 seconds).

Attributes

credentials

The current temporary AWS security credentials.

cache

(SessionCache) The client and resource cache used to store and retrieve cached clients.

Methods

client(*args, eviction_policy: EvictionPolicy, max_size: int, **kwargs) -> BaseClient

Creates a low-level service client by name.

get_identity() -> Identity

Returns metadata about the current caller identity.

refreshable_credentials() -> TemporaryCredentials

Returns the current temporary AWS security credentials.

resource(*args, eviction_policy: EvictionPolicy, max_size: int, **kwargs) -> ServiceResource

Creates a low-level service resource by name.

whoami() -> Identity

Alias for get_identity.

Other Parameters:
**kwargsAny, optional

Optional keyword arguments for the boto3.session.Session object.

Raises:
BRSConfigurationError

If the provided parameters are in an invalid or inconsistent state (e.g. missing MFA SerialNumber when mfa_token_provider is given, etc.) or if the MFA token command fails to execute properly.

BRSValidationError

If the provided parameters are of incorrect types or if required parameters are missing.

Notes

Note

For additional details on configuring MFA, refer to the MFA usage documentation.

Note

For additional details on client and resource caching, refer to the caching documentation.

Examples

Basic initialization using AssumeRoleConfig:

>>> from boto3_refresh_session import (
...     AssumeRoleConfig, STSRefreshableSession
... )
>>> session = STSRefreshableSession(
...     assume_role_kwargs=AssumeRoleConfig(RoleArn="<your-role-arn>")
... )

MFA with dynamic tokens (recommended). Provide SerialNumber and a token provider (callable or CLI command). The provider is invoked on each refresh and its 6-digit token overrides any TokenCode:

>>> assume_role = AssumeRoleConfig(
...     RoleArn="<your-role-arn>",
...     SerialNumber="arn:aws:iam::<account-id>:mfa/<user-name>",
... )
... # using a simple lambda function as the token provider
>>> session = STSRefreshableSession(
...     assume_role_kwargs=assume_role,
...     mfa_token_provider=lambda: "123456",
... )
... # or using a CLI command to get the token from a YubiKey OATH app
>>> session = STSRefreshableSession(
...     assume_role_kwargs=assume_role,
...     mfa_token_provider=["ykman", "oath", "code", "<your-issuer>"],
...     mfa_token_provider_kwargs={"timeout": 45},  # custom timeout
... )
property available_profiles[source]#

The profiles available to the session credentials

client(*args, eviction_policy: Literal['LRU', 'LFU'] | None = None, max_size: int | None = None, **kwargs) BaseClient[source]#

Returns a cached client from the default session if it exists, otherwise creates a new client and caches it.

Added in version 2.1.0.

Parameters:
eviction_policyEvictionPolicy, optional

The type of cache to create. Case sensitive. Options are “LRU” and “LFU”. Defaults to “LRU”.

max_sizeint | None, optional

The maximum size of the client cache. If None, the cache size is unlimited. Beware that modifying this value after the cache has already been initialized may evict existing clients. Default is None.

*args

Positional arguments to be passed to the default session’s client method. Check boto3.session.Session.client for more details on accepted arguments.

**kwargs

Keyword arguments to be passed to the default session’s client method. Check boto3.session.Session.client for more details on accepted arguments.

Returns:
BaseClient

A cached client if it exists, otherwise a new client that has been cached.

Raises:
ClientCacheError

Raised when an error occurs related to cache operations, such as using an invalid key, eviction policy, or value type.

ClientCacheExistsError

Raised when attempting to add a client which already exists in the cache.

ClientCacheNotFoundError

Raised when attempting to retrieve or delete a client which does not exist in the cache.

Examples

>>> from boto3_client_cache import client
>>> s3_client = client("s3", region_name="us-east-1")
>>> s3_client_again = client("s3", region_name="us-east-1")
>>> s3_client is s3_client_again
True
property credentials: TemporaryCredentials[source]#

The current temporary AWS security credentials.

Alias for refreshable_credentials.

property events[source]#

The event emitter for a session

get_available_partitions()[source]#

Lists the available partitions

Return type:

list

Returns:

Returns a list of partition names (e.g., [“aws”, “aws-cn”])

get_available_regions(service_name, partition_name='aws', allow_non_regional=False)[source]#

Lists the region and endpoint names of a particular partition.

The list of regions returned by this method are regions that are explicitly known by the client to exist and is not comprehensive. A region not returned in this list may still be available for the provided service.

Parameters:
  • service_name (string) – Name of a service to list endpoint for (e.g., s3).

  • partition_name (string) – Name of the partition to limit endpoints to. (e.g., aws for the public AWS endpoints, aws-cn for AWS China endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc.)

  • allow_non_regional (bool) – Set to True to include endpoints that are not regional endpoints (e.g., s3-external-1, fips-us-gov-west-1, etc).

Returns:

Returns a list of endpoint names (e.g., [“us-east-1”]).

get_available_resources()[source]#

Get a list of available services that can be loaded as resource clients via Session.resource.

Return type:

list

Returns:

List of service names

get_available_services()[source]#

Get a list of available services that can be loaded as low-level clients via Session.client.

Return type:

list

Returns:

List of service names

get_credentials()[source]#

Return the botocore.credentials.Credentials object associated with this session. If the credentials have not yet been loaded, this will attempt to load them. If they have already been loaded, this will return the cached credentials.

get_partition_for_region(region_name)[source]#

Lists the partition name of a particular region.

Parameters:

region_name (string) – Name of the region to list partition for (e.g., us-east-1).

Return type:

string

Returns:

Returns the respective partition name (e.g., aws).

property profile_name[source]#

The read-only profile name.

refreshable_credentials() TemporaryCredentials[source]#

Returns the current temporary AWS security credentials.

Returns:
TemporaryCredentials
Temporary AWS security credentials containing:
access_keystr

AWS access key identifier.

secret_keystr

AWS secret access key.

tokenstr

AWS session token.

expiry_timestr

Expiration timestamp in ISO 8601 format.

property region_name[source]#

The read-only region name.

resource(*args, eviction_policy: Literal['LRU', 'LFU'] | None = None, max_size: int | None = None, **kwargs) ServiceResource[source]#

Returns a cached resource from the default session if it exists, otherwise creates a new resource and caches it.

Added in version 2.1.0.

Parameters:
eviction_policyEvictionPolicy, optional

The type of cache to create. Case sensitive. Options are “LRU” and “LFU”. Defaults to “LRU”.

max_sizeint | None, optional

The maximum size of the resource cache. If None, the cache size is unlimited. Beware that modifying this value after the cache has already been initialized may evict existing resources. Default is None.

*args

Positional arguments to be passed to the default session’s resource method. Check boto3.session.Session.resource for more details on accepted arguments.

**kwargs

Keyword arguments to be passed to the default session’s resource method. Check boto3.session.Session.resource for more details on accepted arguments.

Returns:
ServiceResource

A cached resource if it exists, otherwise a new resource that has been cached.

Raises:
ResourceCacheError

Raised when an error occurs related to cache operations, such as using an invalid key, eviction policy, or value type.

ResourceCacheExistsError

Raised when attempting to add a resource which already exists in the cache.

ResourceCacheNotFoundError

Raised when attempting to retrieve or delete a resource which does not exist in the cache.

Notes

Tip

For correct typing, you may want to import mypy-boto3-* and use the generated type annotations for casting clients, which will be compatible with this method.

Examples

>>> from boto3_client_cache import resource
>>> s3_resource = resource("s3", region_name="us-east-1")
>>> s3_resource_again = resource("s3", region_name="us-east-1")
>>> s3_resource is s3_resource_again
True
whoami() Identity[source]#

Returns metadata about the current caller identity.

Added in version 7.2.15.

Note

This method is an alternative to get_identity().

Returns:
Identity

Dict containing current caller identity metadata.

get_identity() Identity[source]#

Returns metadata about the identity assumed.

Returns:
Identity

Dict containing caller identity according to AWS STS.