boto3 Sessions, and Why You Should Use Them

s3 = boto3.client('s3')
ddb = boto3.resource('dynamodb')
session = boto3.Session()
s3 = session.client('s3')
ddb = session.resource('dynamodb')
import boto3
sts = boto3.client('sts')
print(sts.get_caller_identity())
def client(*args, **kwargs):
return _get_default_session().client(*args, **kwargs)
def _get_default_session():
if DEFAULT_SESSION is None:
setup_default_session()
return DEFAULT_SESSION
def setup_default_session(**kwargs):
DEFAULT_SESSION = Session(**kwargs)
import boto3
sts = boto3.client('sts')
print(sts.get_caller_identity())
def greet(table_name, user_id):
ddb = boto3.resource('dynamodb')
table = ddb.Table(table_name)
item = table.get_item(Key={'id': user_id})
print('Hello {}'.format(item['Item']['name']))
def greet(table_name, user_id, region=None):
ddb = boto3.resource('dynamodb', region_name=region)
table = ddb.Table(table_name)
item = table.get_item(Key={'id': user_id})
print('Hello {}'.format(item['Item']['name']))
def greet(session, table_name, user_id):
ddb = session.resource('dynamodb', region_name=region)
table = ddb.Table(table_name)
item = table.get_item(Key={'id': user_id})
print('Hello {}'.format(item['Item']['name']))
def greet(table_name, user_id, session=None):
if not session:
session = boto3._get_default_session()
ddb = session.resource('dynamodb', region_name=region)
table = ddb.Table(table_name)
item = table.get_item(Key={'id': user_id})
print('Hello {}'.format(item['Item']['name']))
parser = argparse.ArgumentParser()
# other args...
parser.add_argument('--profile')
args = parser.parse_args()
session = boto3.Session(profile_name=args.profile)# body of the script, using the session...
[profile my-base-profile]
# Set up in whatever your usual fashion is
[profile my-assumed-role-profile]
role_arn = arn:aws:iam::123456789012:role/MyRoleToAssume
source_profile = my-base-profile
# or on EC2 instance/ECS, you might do one of:
# credential_source = Ec2InstanceMetadata
# credential_source = EcsContainer
base_session = boto3.Session(profile_name='my-base-profile')
print(base_session.client('sts').get_caller_identity())
# will show your normal identity
# independent of the above code
assumed_role_session = boto3.Session(profile_name='my-assumed-role-profile')
print(assumed_role_session.client('sts').get_caller_identity())
# will show that you're using MyRoleToAssume
sts = boto3.client('sts')
response = sts.assume_role(
RoleArn='arn:aws:iam::123456789012:role/MyRoleToAssume',
RoleSessionName='my-session'
)
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"],
region='people vary a ton in how they set this'
)
base_session = boto3.Session()
# or any other config for a session, e.g.
# base_session = boto3.Session(profile_name='my-base-profile')
assumed_role_session = aws_assume_role_lib.assume_role(session, 'arn:aws:iam::123456789012:role/MyRoleToAssume')
aws_assume_role_lib.patch_boto3()assumed_role_session = boto3.assume_role('arn:aws:iam::123456789012:role/MyRoleToAssume')# or
base_session = boto3.Session()
assumed_role_session = base_session.assume_role( 'arn:aws:iam::123456789012:role/MyRoleToAssume')
import argparse
import boto3
parser = argparse.ArgumentParser()parser.add_argument('--profile', help='Use a specific AWS config profile')args = parser.parse_args()session = boto3.Session(profile_name=args.profile_name)# use the session

--

--

--

Cloud Robotics Research Scientist at @iRobot

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

kubectl commands cheatsheet

Secure EC2 cross account access to AWS resources

Plutos Network Launches User Dashboard and PlutButton Game.

RetailMeNot 💜 GraphQL Federation

Algorithm practice: The matrix unroll

Ledge Grab System: Part V

Datadog Brings Application Monitoring to AWS App Runner

Getting started with Kerberos

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ben Kehoe

Ben Kehoe

Cloud Robotics Research Scientist at @iRobot

More from Medium

The Mystery of Folders on AWS S3

Lambda UDFs for Amazon Redshift

Working with Amazon S3 Object Lambda

AWS Lambda Cookbook — Elevate your handler’s code — Part 4 — Environment Variables