Skip to content

Instantly share code, notes, and snippets.

@p120ph37
Created March 11, 2025 22:44
Show Gist options
  • Save p120ph37/01b3b6dff842d6b5b5c3a967a96c8923 to your computer and use it in GitHub Desktop.
Save p120ph37/01b3b6dff842d6b5b5c3a967a96c8923 to your computer and use it in GitHub Desktop.
Python script to discover which roles you can assume in an AWS account
import boto3
import botocore
stsc = boto3.client('sts')
iamc = boto3.client('iam')
iamr = boto3.resource('iam')
iam_paginator = iamc.get_paginator('list_roles')
iam_page_iterator = iam_paginator.paginate()
iam_user_arn = 'arn:aws:iam::369786485381:user/ameriwether' # iam_user.arn
for page in iam_page_iterator:
roles = page['Roles']
for role in roles:
role_arn = role['Arn']
try:
resp = stsc.assume_role(
RoleArn=role_arn,
RoleSessionName=('test-' + role['RoleName']),
DurationSeconds=900,
)
print(' IS ALLOWED: '+role['RoleName'])
except botocore.exceptions.ClientError:
print('not allowed '+role['RoleName'])
@p120ph37
Copy link
Author

Will only work if your user has the ListRoles permission in the first place. Tries to assume all the roles, and tells you which ones worked. Uses your existing credentials from ~/.aws/credentials or the current-machine identity in EC2 if there is no ~/.aws/credentials file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment