3

By default boto3 creates sessions whenever required, according to the documentation

it is possible and recommended to maintain your own session(s) in some scenarios

My understanding is if I use a session created by me I can reuse the same session across the application instead of boto3 automatically creating multiple sessions or if I want to pass credentials from code.

Has anyone ever maintained sessions on their own? If yes what was the advantage that it provided apart from the one mentioned above.

secrets_manager = boto3.client('secretsmanager')
session = boto3.session.Session()
secrets_manager = session.client('secretsmanager')

Is there any advantage of using one over the other and which one is recommended in this case.

References: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/session.html

2 Answers2

2

I have seen the second method used when you wish to provide specific credentials without using the standard Credentials Provider Chain.

For example, when assuming a role, you can use the new temporary to create a session, then create a client from the session.

From boto3 sessions and aws_session_token management:

import boto3

role_info = {
    'RoleArn': 'arn:aws:iam::<AWS_ACCOUNT_NUMBER>:role/<AWS_ROLE_NAME>',
    'RoleSessionName': '<SOME_SESSION_NAME>'
}

client = boto3.client('sts')
credentials = client.assume_role(**role_info)

session = boto3.session.Session(
    aws_access_key_id=credentials['Credentials']['AccessKeyId'],
    aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
    aws_session_token=credentials['Credentials']['SessionToken']
)

You could then use: s3 = session.client('s3')

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
0

Here is an example where I needed to use the session object with both Boto3 and AWS Datawrangler to set the region for both:

REGION = os.environ.get("REGION")

session = boto3.Session(region_name=REGION)
client_rds = session.client("rds-data")

df = wr.s3.read_parquet(path=path, boto3_session=session)
abk
  • 309
  • 6
  • 15