List users from multiple AWS accounts using Python

 
 

List users from multiple AWS accounts using Python is our next tutorial where we will learn how to access AWS APIs using Boto3 package and also how to use pprint package to list all results in a easy to read format, we heard about the term human readable too but we think is not the right way of saying it, at least not in this particular case. Please rest assured that we won’t talk or debate in this tutorial about what Cloud Hosting provider is the best or not and we will simply resume talking about how to get all user accounts from multiple AWS accounts, their groups, roles, particular policies and also if they have MFA (Multi Factor Authentication) devices enabled or not for their individual accounts. For this tutorial we have used Python 3.6 installed on a CentOS 7 server but the same should work with Python 3.7 or even a higher version, on any operating systems like MacOS, Linux or Windows that have one of these Python versions installed, no worries Docker is a good candidate too for running this Python example, it’s up to you, feel free to use any operating system. Be aware that Boto3 and pprint modules must be installed as well using pip utility before running the next Python code.

Table of contents

Import Python modules
Define AWS accounts as dictionary
Looping through AWS accounts and user accounts

Import Python modules

Assuming that both necessary modules were installed properly, boto3 and pprint then we can begin with our very first step by importing these two modules like shown in the next lines below:


import boto3
from pprint import pprint

Define AWS accounts as dictionary

Next let’s define our AWS accounts and credentials like shown below using Python dictionaries for this. Before begin please make sure that on each of these AWS accounts you have created a user, access key id and also a secret key access, if not please generate those first before proceeding with this step otherwise the code will fail. For this particular tutorial we have used three AWS accounts to show you how to loop through these AWS accounts using for statement but please feel free to add as many accounts as you want.


aws_accounts = {

    1: {
        'aws_aka': 'First AWS Account Name',
        'aws_aki': '[access_key_id]',
        'aws_sak': '[secret_access_key]'
    },

    2: {
        'aws_aka': 'Second AWS Account Name',
        'aws_aki': '[access_key_id]',
        'aws_sak': '[secret_access_key]'
    },

    3: {
        'aws_aka': 'Third AWS Account Name',
        'aws_aki': '[access_key_id]',
        'aws_sak': '[secret_access_key]'
        }
                }

As you can notice we have used three values for our dictionary, first one called aws_aka which represents the account name, second value aws_aki representing Access Key ID for that particular user that’s authorised to perform API calls and the third value being aws_sak that represents Secret Access Key for the same username delegated to perform API calls within each AWS accounts in order to get AWS users list, their groups, roles, policies and also if they have MFA (Multi Factor Authentication) devices enabled or not.

Looping through AWS accounts and user accounts

On the next step we will perform two loops, first loop will be used to connect to each individual AWS accounts that we have defined previously on our dictionary and the second loop will help us get the users list and their details from the current AWS account within the loop. At this stage Boto3 module plays a very important role as this will facilitate actually the connection between our application and all defined AWS environments and also it will extract all requested data from these accounts.


for aws_current_account in aws_accounts.items():

    client = boto3.client(
        'iam',
        aws_access_key_id=aws_current_account[1]['aws_aki'],
        aws_secret_access_key=aws_current_account[1]['aws_sak']
    )

    users = client.list_users()
    user_list = []
    user_count = 0

    try:

        print("\n----==[ AWS Account Name:", aws_current_account[1]['aws_ana'], "]==----\n")

        for key in users['Users']:
            result = {}
            groups = []
            policies = []

            result['Username'] = key['UserName']

            policies_list = client.list_user_policies(UserName=key['UserName'])
            result['Policies Attached'] = policies_list['PolicyNames']

            groups_list = client.list_groups_for_user(UserName=key['UserName'])

            for group in groups_list['Groups']:
                groups.append(group['GroupName'])
            result['Groups List'] = groups

            mfa_devices_list = client.list_mfa_devices(UserName=key['UserName'])

            if not len(mfa_devices_list['MFADevices']):
                result['MFA Device Configured'] = False
            else:
                result['MFA Device Configured'] = True
            user_list.append(result)

        for key in user_list:
            user_count = user_count + 1
            print("\n User Account Number:", user_count)
            print("- - - - - - - - - -")
            pprint(key)
            print("- - - - - - - - - -\n")

    except Exception as error:
        print(error)

To test this application you will simply need to copy all three code sections in a Python file and to give it a go.
That is all for now, our short tutorial about how to get users from multiple AWS accounts using Python ends here.

Video

No video posted for this page.

Screenshots

No screenshots posted for this page.

Source code

No code posted for this page.

About this page

Article
List users from multiple AWS accounts using Python
Author
Category
Published
13/11/2018
Updated
14/11/2018
Tags

Share this page

If you found this page useful please share it with your friends or colleagues.