Skip to content

Instantly share code, notes, and snippets.

@keithrozario
Created September 22, 2021 07:06
Show Gist options
  • Save keithrozario/3748af20acf7ba5152fb3aef315cfd17 to your computer and use it in GitHub Desktop.
Save keithrozario/3748af20acf7ba5152fb3aef315cfd17 to your computer and use it in GitHub Desktop.
Check which users are not in groups
import boto3
iam = boto3.resource('iam')
def list_users() -> list:
"""
List all users in an account
:return: list of usernames
"""
usernames = []
client = boto3.client("iam")
paginator = client.get_paginator('list_users')
for response in paginator.paginate():
for user in response["Users"]:
usernames.append(user['UserName'])
return usernames
def list_groups() -> list:
"""
List all groups in an account
:return: list of group names
"""
group_names = []
client = boto3.client("iam")
paginator = client.get_paginator('list_groups')
for response in paginator.paginate():
for user in response["Groups"]:
group_names.append(user['GroupName'])
return group_names
all_usernames = list_users()
print(f"Total of {len(all_usernames)} users found")
all_groups = list_groups()
print(f"Total of {len(all_groups)} groups found")
# Find all users in all groups
usernames_in_group = []
for group in all_groups:
iam_group = iam.Group('GroupA')
user_iterator_A = iam_group.users.all()
for user in user_iterator_A:
usernames_in_group.append(user.user_name)
users_not_in_groups = set(all_usernames) ^ set(usernames_in_group)
print(f"Found {len(users_not_in_groups)} users not beloging to any groups")
print(users_not_in_groups)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment