Role assumption in AWS allows users and services to obtain temporary credentials to perform actions that their own profiles don’t allow. Using boto3, you can programmatically assume a role, granting your application temporary access to AWS resources.

Basic Scenario

import boto3
# Creating an STS client
sts_client = boto3.client('sts')
# Assuming a role
assumed_role = sts_client.assume_role(
    RoleArn='arn:aws:iam::123456789012:role/YourRoleName',
    RoleSessionName='YourSessionName'
)
# Accessing temporary credentials
credentials = assumed_role['Credentials']

This code snippet demonstrates how to assume a role and access the temporary credentials it provides.

Now, you can use these credentials to set up a different boto3 session (example below).

Advanced Scenarios

Assuming Roles in Different Accounts

Often, you might need to assume a role in a different AWS account. This is crucial for cross-account access. The process is similar, but you specify the ARN of the role in the target account:

# Assuming a role in another account
other_account_role = sts_client.assume_role(
    RoleArn='arn:aws:iam::OTHER_ACCOUNT_ID:role/OtherAccountRoleName',
    RoleSessionName='YourSessionName'
)

Creating Sessions with Assumed Roles

You might want to create a session with the assumed role’s credentials for extended tasks. This is done as follows:

session = boto3.Session(
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken']
)

This session can now interact with AWS services as the assumed role.

Switching Roles in Boto3

Switching roles is essential when your application needs different access levels at different times. This can be achieved by repeating the role assumption process with different role ARNs and creating new sessions as needed.

To put it into practice, here’s an example where we assume a role and then list S3 buckets:

# Assume role as before
# ...
# Create a session with the assumed role credentials
session = boto3.Session(
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken']
)
# Use the session to create an S3 client
s3 = session.client('s3')
# List S3 buckets
buckets = s3.list_buckets()
print(buckets)

Conclusion

Role assumption with Boto3 in AWS is a powerful feature, enabling flexible and secure access management. Whether you’re accessing resources in your account or another account or switching roles dynamically, Boto3 makes it straightforward. By understanding and applying these concepts, you can enhance the security and efficiency of your AWS-based applications.