Boto3 Single Session across the project

How to create a single boto3 session and use it across a python project? Here is the solution:
Create session.py
Paste the following code:

import boto3
import os


class Session:
    session = None

    def __init__(self):
        self.get_session()

    @classmethod
    def get_session(cls):
        if cls.session is None:
            cls.session = cls.start_session()
        return cls.session

    @staticmethod
    def start_session():
        if 'AWS_ROLE_ACCESS_KEY' in os.environ:
            session = boto3.session.Session(
                aws_access_key_id=os.environ['AWS_ROLE_ACCESS_KEY'],
                aws_secret_access_key=os.environ['AWS_ROLE_SECRET_KEY'],
                aws_session_token=os.environ['AWS_ROLE_SESSION_TOKEN']
            )
        else:
            session = boto3.session.Session()
        return session

Use the session in any file as follows:

from session import Session

class SomeModule:

    def __init__(self):
        self.session = Session.get_session()
        self.ecr_client = self.session.client('ecr')

Leave a Reply

Your email address will not be published. Required fields are marked *