Update session credentials on boto3 client rather than recreating the client

17 Views Asked by At

Is there a standard way to update the session details on a boto3 client without recreating the whole client?

class MyClass:
    def __init__(self):
        self.iam_role = os.environ["IAM_ROLE_ARN"]
        self.sts_client = boto3.client("sts")
        self.dynamodb_client = boto3.client("dynamodb")

        self.refresh_dynamodb_session()

    def refresh_dynamodb_session(self):
        sts_session = self.sts_client.assume_role(
            RoleArn=self.iam_role,
            RoleSessionName="dynamodb-session",
        )

        key_id = sts_session["Credentials"]["AccessKeyId"]
        access_key = sts_session["Credentials"]["SecretAccessKey"]
        session_token = sts_session["Credentials"]["SessionToken"]

        # Somehow update the credentials on the dynamodb client
        self.dynamodb_client.update_credentials(
            aws_access_key_id=key_id,
            aws_secret_access_key=access_key,
            aws_session_token=session_token,
        )

    def get_data(self):
        try:
            # Do something...
            pass
        except self.dynamodb_client.exceptions.ExpiredTokenException as e:
            # update the credentials when the token has expired
            self.refresh_dynamodb_session()
            # redrive...
            return self.get_data()

All I've seen in the docs envolves recreating the client every time the token has expired. It feels like unnecessary processing to recreate the entire client when all you want to do is update the token.

0

There are 0 best solutions below