Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List RoleNames based on Action in AssumeRolePolicyDocument using boto3

I am using below python code to list all the IAM Role Names.

from boto3 import Session
import logging
from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)


def list_iam_roles(profile):
    boto_sess = Session(profile_name=profile)
    client = boto_sess.client('iam')

    roles = client.list_roles()
    for role in roles["Roles"]:
        print (role["RoleName"])
    return 

list_iam_roles('some_profile')

It successfully returns the list of the all the IAM Role Names, but my requirement is to filter based on specific AssumeRolePolicyDocument.

I want to filter Role Names which has Action: sts:AssumeRoleWithSAML.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any hints how can I filter it?

The sample output of each role is pasted below. Ciphering some important information already with xxx.

{'Path': '/', 'RoleName': 'some_role_name', 'RoleId': 'some_id', 'Arn': 'arn:aws:iam::xxxxx:role/some_role_name', 'CreateDate': datetime.datetime(2021, 2, 14, 12, 49, 26, tzinfo=tzutc()), 'AssumeRolePolicyDocument': {'Version': '2012-10-17', 'Statement': [{'Sid': '', 'Effect': 'Allow', 'Principal': {'Federated': 'arn:aws:iam::xxxxx:saml-provider/provider_name'}, 'Action': 'sts:AssumeRoleWithSAML', 'Condition': {'StringEquals': {'SAML:aud': 'https://signin.aws.amazon.com/saml'}}}]}, 'MaxSessionDuration': 36000}

>Solution :

One way would be simply to convert your role to string and do string search:


def list_iam_roles(profile):
    boto_sess = Session(profile_name=profile)
    client = boto_sess.client('iam')

    roles = client.list_roles()
    for role in roles["Roles"]:
        if "sts:AssumeRoleWithSAML".lower() in str(role).lower(): 
            print (role["RoleName"])
    return 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading