aws_users_export.py 5.16 KB
import json
import boto3
import argparse

###
# To run this script you need to be authenticated in AWS already.
#
# Export your user access key and password to ~/.aws/credentials
#
#  - or -
#
# If you're running this on an EC2 instance, and the instance has
# role with permissions to read IAM users, you export the profile:
#
# export AWS_DEFAULT_PROFILE=env-name
#
#  - or -
#
# export AWS_ACCESS_KEY_ID=AKIAIO5FODNN7EXAMPLE
# export AWS_SECRET_ACCESS_KEY=ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE
#
#  - or -
#
# Finally, if you just want to hard code your creds, initialize
# your client like this:
#
# client = boto3.client(
#     'iam',
#     aws_access_key_id='AKIAIO5FODNN7EXAMPLE',
#     aws_secret_access_key='ABCDEF+c2L7yXeGvUyrPgYsDnWRRC1AYEXAMPLE'
# )
###

def get_all_headers(data):

    keys = []

    for item in data:
        for key in item.keys():
            if key not in keys:
                keys.append(key)

    return keys

def fetch_user_data(user_list):

    for user in user_list['Users']:

        # Get Group Data
        group_data = client.list_groups_for_user(UserName=user['UserName'])
        user['Groups'] = []

        # Get inline and attached group policies
        for group in group_data['Groups']:

            group_inline_policy_data = client.list_group_policies(GroupName=group['GroupName'])
            group_attached_policy_data = client.list_attached_group_policies(GroupName=group['GroupName'])

            if args.policies:
                group['InlineGroupPolicies'] = []
                for policy in group_inline_policy_data['PolicyNames']:
                    policy_data = client.get_group_policy(GroupName=group['GroupName'], PolicyName=policy)
                    #group['InlineGroupPolicies'][policy] = policy_data['PolicyDocument']
                    group['InlineGroupPolicies'].append(policy_data['PolicyDocument'])

                group['AttachedGroupPolicies'] = []
                for policy in group_attached_policy_data['AttachedPolicies']:
                    policy_data = client.get_policy(PolicyArn=policy['PolicyArn'])
                    policy_doc = client.get_policy_version(PolicyArn=policy['PolicyArn'], VersionId=policy_data['Policy']['DefaultVersionId'])
                    policy_data['Policy']['PolicyDocument'] = policy_doc['PolicyVersion']['Document']
                    group['AttachedGroupPolicies'].append(policy_data['Policy'])
            else:
                group['InlineGroupPolicies'] = group_inline_policy_data['PolicyNames']
                group['AttachedGroupPolicies'] = group_attached_policy_data['AttachedPolicies']

            user['Groups'].append(group)

        user_inline_policy_data = client.list_user_policies(UserName=user['UserName'])
        user_attached_policy_data = client.list_attached_user_policies(UserName=user['UserName'])

        if args.policies:
            user['InlineUserPolicies'] = []
            for policy in user_inline_policy_data['PolicyNames']:
                policy_data = client.get_user_policy(UserName=user['UserName'], PolicyName=policy)
                user['InlineUserPolicies'].append(policy_data['PolicyDocument'])

            user['AttachedUserPolicies'] = []
            for policy in user_attached_policy_data['AttachedPolicies']:
                policy_data = client.get_policy(PolicyArn=policy['PolicyArn'])
                policy_doc = client.get_policy_version(PolicyArn=policy['PolicyArn'], VersionId=policy_data['Policy']['DefaultVersionId'])
                policy_doc = client.get_policy_version(PolicyArn=policy['PolicyArn'], VersionId=policy_data['Policy']['DefaultVersionId'])
                policy_data['Policy']['PolicyDocument'] = policy_doc['PolicyVersion']['Document']
                user['AttachedUserPolicies'].append(policy_data['Policy'])

        else:
            user['InlineUserPolicies'] = user_inline_policy_data['PolicyNames']
            user['AttachedUserPolicies'] = user_attached_policy_data['AttachedPolicies']

        tag_data = client.list_user_tags(UserName=user['UserName'])
        user['Tags'] = tag_data['Tags']

        mfa_data = client.list_mfa_devices(UserName=user['UserName'])
        user['MFADevices'] = mfa_data['MFADevices']

        user_data.append(user)

    return user_data

if __name__ == '__main__':

    # Parse CLI args
    argp = argparse.ArgumentParser(description='Export AWS users to JSON')
    argp.add_argument('--file', '-f', dest='outfile',
                      action='store', help='File to export data into')
    argp.add_argument('--verbose-policies', '-p', dest='policies',
                      action='store_true', help='Export full policy details')
    args = argp.parse_args()

    # Initialize client
    client = boto3.client('iam')

    user_data = []

    user_list = client.list_users()
    user_data += fetch_user_data(user_list)

    while user_list['IsTruncated'] is True:
        user_list = client.list_users(Marker=user_list['Marker'])
        user_data += fetch_user_data(more_users)

    # Dump user data
    out = json.dumps(user_data, default=str, indent=2)

    if args.outfile:
        # Write data to file
        with open(args.outfile, 'w') as f:
            f.write(out)
    else:
        # Print to stdout
        print(out)