This post summarizes how to perform AssumeRole using Boto3.
Introduction
There are many situations where you need to AssumeRole using a Python script with Boto3.
Every time, I end up looking up how to implement it again—so here's a summary of the method.
Note: This article was translated from my original post.
Assuming Roles with Boto3
Implementing the AssumeRole function
Let’s jump right into implementing a Python function to perform AssumeRole.
import boto3 def assume_role(aws_account_number: str, role_name: str) -> boto3.Session: """ Assumes the provided role in the target account and returns Session. Args: - aws_account_number: AWS Account Number - role_name: Role to assume in target account Returns: AssumeRole Session. """ try: sts_client = boto3.client('sts') # Get the current partition partition = sts_client.get_caller_identity()['Arn'].split(":")[1] response = sts_client.assume_role( RoleArn=f'arn:{partition}:iam::{aws_account_number}:role/{role_name}', RoleSessionName=f'SessionFor{role_name}In{aws_account_number}' ) # Storing STS credentials session = boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'] ) except Exception as e: raise ValueError(f'Error in AssumeRole process: {e}') print(f'Assumed session for {role_name} in {aws_account_number}.') return session
This implementation is based on and modified from a script in aws-samples, specifically this one.
The overall flow of this code is:
- Receive the target Role name and AWS account ID as arguments
- Create a Boto3 client for STS
- Call AssumeRole
- Return a Boto3 session using the credentials from AssumeRole
By using the session returned from this function, you can perform actions with the assumed role’s permissions.
Now let’s look at a simple usage example of the AssumeRole function.
Example Usage
Using the assume_role() function, we’ll call the S3 list buckets API under the assumed role.
# Store the required info role_name = 'AssumeRoleTest' # Role name to assume target_account_id = '123456789012' # Target AWS account ID # Get an S3 Boto3 client from the assumed session session = assume_role(target_account_id, role_name) s3_client = session.client('s3') # Execute the API buckets = s3_client.list_buckets() print(buckets)
The main usage pattern is to generate Boto3 clients from the session obtained via assume_role().
In the example above, we create an S3 client, but you can create clients for other services in the same way:
client = session.client('[service-name]')
For more on creating Boto3 clients for each service, refer directly to the documentation:
Boto3 1.40.34 documentation
Conclusion
This was a guide to using AssumeRole with Boto3.
Designing roles with the assumption of using AssumeRole is often important. In large-scale projects operated across multiple accounts, leveraging AssumeRole is essential.
I hope this article helps someone!
[Related Articles]