5 Best Ways to Create an AWS Session Using boto3 Library in Python

Rate this post

πŸ’‘ Problem Formulation: When working with AWS services in Python, developers frequently need to create sessions to manage and automate tasks using AWS resources. The boto3 library is the key to interfacing with AWS using Python. Here we explore how to initiate an AWS session using boto3. As an input, credentials are required (either explicitly or implicitly), and the desired output is an active session with AWS to perform further operations.

Method 1: Using Default Session

This method involves creating a session using the default profile stored in the AWS credentials file or the environment variables. It is straightforward and best suited for simple scripting where only one set of credentials is used. The function boto3.session.Session() initiates a session with the default settings.

Here’s an example:

import boto3

session = boto3.session.Session()
print(session)

The output would be a session object:

<Session region_name='us-west-2'>

This snippet creates a session object with the default AWS credentials and configuration. It is the most direct way to start interacting with AWS services without specifying any additional information.

Method 2: Specifying Custom Credentials

For use cases requiring multiple AWS accounts or special permissions, a session can be created by specifying custom credentials. This method leverages the session class, allowing for tailored access and session configurations using boto3.session.Session() with explicit parameters.

Here’s an example:

import boto3

session = boto3.session.Session(
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    region_name='us-west-2'
)
print(session)

The output would again be a session object:

<Session region_name='us-west-2'>

This code creates a session with explicit credentials, which is useful when dealing with multiple AWS accounts or when needing to override the default credentials programmatically.

Method 3: Using Environment Variables

Environment variables can be used to set AWS credentials securely without hardcoding them into scripts. This method is preferable for keeping sensitive information out of the source code. The boto3 library automatically detects and uses credentials set in environment variables.

Here’s an example:

import boto3
import os

# Assuming environment variables are already set:
# export AWS_ACCESS_KEY_ID='YOUR_ACCESS_KEY'
# export AWS_SECRET_ACCESS_KEY='YOUR_SECRET_KEY'
# export AWS_DEFAULT_REGION='us-west-2'

session = boto3.session.Session()
print(session)

Output remains a session object, with details being sourced from environment variables:

<Session region_name='us-west-2'>

This code creates a session using AWS credentials supplied through environment variables. It’s a secure method for managing credentials and can be easily integrated into deployment pipelines.

Method 4: Using Profiles from AWS Credentials File

Create a session with a named profile from the AWS credentials file. This allows you to easily switch between different AWS accounts and configurations. The named profile contains the necessary credentials and configurations, invoked using boto3.session.Session(profile_name='your_profile').

Here’s an example:

import boto3

session = boto3.session.Session(profile_name='myprofile')
print(session)

Expected output is a session object initialized with the settings from the specified profile:

<Session region_name='us-west-2' profile='myprofile'>

This code initializes a session with the ‘myprofile’ profile’s settings. It’s a clean way to manage multiple sets of credentials and configurations.

Bonus One-Liner Method 5: Using STS Assume Role

When you need to assume a different role, such as for cross-account access, you can use the STS service to switch roles within your session. This is achieved using boto3.client('sts').assume_role(), which returns temporary security credentials.

Here’s an example:

import boto3

sts_client = boto3.client('sts')
assumed_role = sts_client.assume_role(
    RoleArn="arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME",
    RoleSessionName="AssumedRoleSession"
)
print(assumed_role)

The output is a dictionary with temporary security credentials:

{
    'Credentials': {
        'AccessKeyId': 'ASIA...',
        'SecretAccessKey': '...',
        'SessionToken': '...',
        'Expiration': '...'
    },
    ...
}

This code snippet demonstrates how to assume a different IAM role, providing temporary credentials that can be used to create a new session.

Summary/Discussion

  • Method 1: Default Session. Easy and straightforward. Limited to default credentials.
  • Method 2: Custom Credentials. Flexible with explicit parameters. Requires handling sensitive information in the script.
  • Method 3: Environment Variables. Secure and separate from code. Requires additional setup and management of environment variables.
  • Method 4: Profiles from AWS Credentials File. Convenient for switching between accounts. Dependency on the configuration of the local AWS credentials file.
  • Method 5: Using STS Assume Role. Powerful for advanced use cases like cross-account access. More complex and requires management of temporary credentials.