I need to fetch all the aws user\'s, their corresponding groups, policies and then if mfa is activated for them or not. Can anyone tell me how it can be done via aws cli or
Here, I am using boto commands to do four operations -
Get IAM connection to AWS Account
import boto3
client = boto3.client('iam',aws_access_key_id="XXX",aws_secret_access_key="XXX")
Getting IAM Users This will print all the usernames. you can customize if you want to print other details as well.
users = client.list_users()
for key in users['Users']:
print key['UserName']
Getting List of Policy attached to each user
for key in users['Users']:
List_of_Policies = client.list_user_policies(UserName=key['UserName'])
for key in List_of_Policies['PolicyNames']:
print key['PolicyName']
Getting List of Groups attached to each user
for key in users['Users']:
List_of_Groups = client.list_groups_for_user(UserName=key['UserName'])
for key in List_of_Groups['Groups']:
print key['GroupName']
Checking if MFA Device is configured or not
for key in users['Users']:
List_of_MFA_Devices = client.list_mfa_devices(UserName=key['UserName'])
for key in List_of_MFA_Devices['MFADevices']:
print key
You can further check if List_of_MFA_Devices['MFADevices'] is empty or not. If empty, then MFA Device is not configured.
If you want to add output as List of Dict where each index will contain dict have value pairs for userName, Groups, Policy, isMFA_flag_configured or not. Use the following code -
import boto3
client = boto3.client('iam',aws_access_key_id="XXXX",aws_secret_access_key="YYY")
users = client.list_users()
user_list = []
for key in users['Users']:
result = {}
Policies = []
Groups=[]
result['userName']=key['UserName']
List_of_Policies = client.list_user_policies(UserName=key['UserName'])
result['Policies'] = List_of_Policies['PolicyNames']
List_of_Groups = client.list_groups_for_user(UserName=key['UserName'])
for Group in List_of_Groups['Groups']:
Groups.append(Group['GroupName'])
result['Groups'] = Groups
List_of_MFA_Devices = client.list_mfa_devices(UserName=key['UserName'])
if not len(List_of_MFA_Devices['MFADevices']):
result['isMFADeviceConfigured']=False
else:
result['isMFADeviceConfigured']=True
user_list.append(result)
for key in user_list:
print key
Output for the above code -
{'userName': 'user1', 'Groups': ['grp1','grp2'], 'Policies':['policy1','policy2], 'isMFADeviceConfigured': False/True}
{'userName': 'user2', 'Groups': ['grp1','grp2'], 'Policies': ['policy1','policy2], 'isMFADeviceConfigured': False/True}