How to create an AWS session using Boto3 library in Python?


When a user wants to use AWS services using lambda or programming code, a session needs to set up first to access AWS services.

An AWS session could be default as well as customized based on needs.

Problem Statement − Use Boto3 library in Python to create an AWS session.

Approach/Algorithm to solve this problem

Step 1 − To create an AWS session, first set up authentication credentials. Users can find it in IAM console or alternatively, create the credential file manually. By default, its location is at ~/.aws/credentials

Example

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
aws_session_token = YOUR_SESSION_TOKEN
region = REGION_NAME

Step 2 − Install Boto3 using the command - pip install boto3

Step 3 − Import the Boto3 library.

Step 4 − If creating the session with default credential, use Session() with no parameter.

Step 5 − If session is customized, pass the following parameters −

  • aws_access_key_id (string) -- AWS access key ID

  • aws_secret_access_key (string) -- AWS secret access key

  • aws_session_token (string) -- AWS temporary session token

  • region_name (string) -- Default region when creating new connections

  • profile_name (string) -- The name of a profile to use. If not given, then the default profile is used.

Example

The following code creates an AWS session for default as well as customized credentials −

import boto3
# To create default session:
def create_aws_session():
session = boto3.session.Session()
#it creates the default session and can use to connect with any AWS service
   return session
print(create_aws_session())

# To Create customized session:
def create_customized_session(aws_access_key, aws_secret_key, aws_token,
region_name=None,profile_name=None):
   session = boto3.session.Session(aws_access_key_id=aws_access_key,
                                   aws_secret_access_key=aws_secret_key,
                                   aws_session_token = aws_token,
                                   region_name=region_name,
                                   profile_name = profile_name)
   # Here, region_name and profile_name are optional parameters and default value is None
   Print(session)
return session

Output

#if default region_name is not present or NONE and region_name is not
passed in #credential file/calling parameter
Session(region_name=None)
Session(region_name=None)
#if default region_name is present and region_name is passed in
credential file/calling #parameter
Session(region_name=YOUR_REGION_NAME)
Session(region_name= YOUR_REGION_NAME)

Updated on: 22-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements