buildmaestro
buildmaestro

Reputation: 1456

AWS Boto show all roles

Trying to list all roles in account so I can attach a policy. I'm reading through the boto3 documentation but I'm not seeing a method to return a collection of roles in an account.

Is this possible?

Upvotes: 3

Views: 14850

Answers (5)

barryku
barryku

Reputation: 2584

Similar to other's suggestions, you will need iterating the result if more than 1,000 roles are found. The default is 100 at a time, but you can configure MaxItems up to 1000. It's easier to collect all roles in an array, and process them after all iterations.

import boto3
aws_profile = 'YourProfileName'
session = boto3.Session(profile_name=aws_profile)
client = session.client('iam')

roles = []
response = client.list_roles()
roles.extend(response['Roles'])
while 'Marker' in response.keys():
    response = client.list_roles(Marker = response['Marker'])
    roles.extend(response['Roles'])

print('roles found: ' + str(len(roles)))  
for role in roles:
    print(role['RoleName'])
    print(role['Arn'])

Upvotes: 3

Arora20
Arora20

Reputation: 1063

As per your question - you need to attach the policy to the roles. For that, first, you are getting all the roles from the account. you may need any of the below two things to attach the policy to the specific role.

  • Role Name
  • Arn

Below code can help you- I am making a IAM connection and getting the all roles from the account. Since, You will get output in the form of Dicts and Array, you need to extract the arn or name

import boto3
client = boto3.client('iam',aws_access_key_id="XXXXX",aws_secret_access_key="YYYYY")
roles = client.list_roles()
Role_list = roles['Roles']
for key in Role_list:
    print(key['RoleName'])
    print(key['Arn'])

Upvotes: 10

0xc0de
0xc0de

Reputation: 8317

There is a method in the API, here it is documented.

Example:

response = client.list_roles(
    PathPrefix='string',
    Marker='string',
    MaxItems=123
)

Upvotes: 0

Chenna
Chenna

Reputation: 62

iam_client =boto3.client('iam',aws_access_key_id=credentials['AccessKeyId'], `enter code here`aws_secret_access_key=credentials['SecretAccessKey'], `enter code here`aws_session_token=credentials['SessionToken'],)
    role_names=[]
    response = iam_client.list_roles(
                PathPrefix='/',
                MaxItems=80 )
    print(response)
    roles = response['Roles']
    for role in roles:
            print(role['Arn'])
            role_names.append(role['RoleName'])
    if response['IsTruncated']:
        response2=iam_client.list_roles(
                    PathPrefix='/',
                    Marker=response['Marker'],
                    MaxItems=80 )
        roles2 = response2['Roles']
        for role2 in roles2:
                print(role2['Arn'])
                role_names.append(role2['RoleName'])
        print(response2)
    if response2['IsTruncated']:
        response3=iam_client.list_roles(
                    PathPrefix='/',
                    Marker=response2['Marker'],
                    MaxItems=80 )
        roles3 = response3['Roles']
        for role3 in roles3:
                print(role2['Arn'])
                role_names.append(role3['RoleName'])
        print(response3)
    print(role_names)
    clearlist(role_names)

Upvotes: 0

buildmaestro
buildmaestro

Reputation: 1456

Here's what I came up with. Replace CAPS values with your actual values.

attach an inline policy to all roles within an account

#!/usr/bin/env python
# Author: Nick Skitch 

import boto3
import json


def main():

    boto3.setup_default_session(profile_name=PROFILE_NAME)
    client = boto3.client('iam')
    policy_document = get_policy_body(IAM_POLICY_JSON)

    roles = get_roles(client)

    for role in roles:
        update_role(role,client,"required_tags",policy_document)

def get_policy_body(data_file):
    with open(data_file) as data_file:
        data = data_file.read()
    return data

def update_role(role_name, client,iam_policy_name,policy_document):
    response = client.put_role_policy(
    RoleName=role_name,
    PolicyName=iam_policy_name,
    PolicyDocument=policy_document
    )

    print response

def get_roles(client):
    client = boto3.client('iam')
    response = None
    role_names = []
    marker = None

    # By default, only 100 roles are returned at a time.
    # 'Marker' is used for pagination.
    while (response is None or response['IsTruncated']):
        # Marker is only accepted if result was truncated.
        if marker is None:
            response = client.list_roles()
        else:
            response = client.list_roles(Marker=marker)

        roles = response['Roles']
        for role in roles:
            print(role['Arn'])
            role_names.append(role['RoleName'])

        if response['IsTruncated']:
            marker = response['Marker']

    return role_names



if __name__ == "__main__":
    main()

Upvotes: -1

Related Questions