Skip to content

Instantly share code, notes, and snippets.

@deeso
Last active September 15, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deeso/8f1e62769988f509505ca40963748781 to your computer and use it in GitHub Desktop.
Save deeso/8f1e62769988f509505ca40963748781 to your computer and use it in GitHub Desktop.
import json
import sys
import os
import boto3
import argparse
parser = argparse.ArgumentParser(description='Easy Fng Button for AWS Role Gneration.')
parser.add_argument('-aws_name', type=str, default='UNKNOWN_NAME',
help='account name')
parser.add_argument('-aws_id', type=str, default='UNKNOWN_ID',
help='account id')
parser.add_argument('-aws_key', type=str, default=os.environ.get('AWS_ACCESS_KEY_ID', None),
help='aws access key id')
parser.add_argument('-aws_secret', type=str, default=os.environ.get('AWS_SECRET_ACCESS_KEY', None),
help='aws secret')
parser.add_argument('-aws_token', type=str, default=os.environ.get('AWS_SESSION_TOKEN', None),
help='aws token')
if __name__ == "__main__":
args = parser.parse_args()
aws_name = args.aws_name
aws_id = args.aws_id
if args.aws_key:
os.environ['AWS_ACCESS_KEY_ID'] = args.aws_key
if args.aws_secret:
os.environ['AWS_SECRET_ACCESS_KEY'] = args.aws_secret
if args.aws_token:
os.environ['AWS_SESSION_TOKEN'] = args.aws_token
if args.aws_token is None:
print("missing aws credentials")
sys.exit()
client = boto3.client('iam')
print("Getting the accounts user list")
response = client.list_users()
users = response['Users']
groups_users = {}
users_groups = {}
groups_attached_policies = {}
groups_policies = {}
print("Getting the users group list")
for user in users:
UserName = user['UserName']
response = client.list_groups_for_user(UserName=UserName)
groups = response['Groups']
users_groups[UserName] = set()
for group in groups:
GroupName = group['GroupName']
if GroupName not in groups_users:
groups_users[GroupName] = set()
groups_users[GroupName].add(UserName)
users_groups[UserName].add(GroupName)
groups_attached_policies = {}
groups_policies = {}
groups_policies_arns = {}
groups_policies_names = {}
attached_policies_groups = {}
policy_arn = {}
for GroupName in groups_users:
response = client.list_attached_group_policies(GroupName=GroupName)
policies = response['AttachedPolicies']
groups_attached_policies[GroupName] = policies
response = client.list_group_policies(GroupName=GroupName)
policies = response['PolicyNames']
groups_policies[GroupName] = policies
groups_policies_arns = {k:set() for k in groups_attached_policies}
groups_policies_names = {k:set() for k in groups_attached_policies}
for GroupName, attached_policies in groups_attached_policies.items():
for info in attached_policies:
PolicyName = info["PolicyName"]
PolicyArn = info["PolicyArn"]
if not PolicyArn in groups_policies_arns:
groups_policies_names[GroupName].add(PolicyName)
groups_policies_arns[GroupName].add(PolicyArn)
# users ===
def users_eq(lhs, rhs):
return lhs == rhs
print("Matching Similar Users, relevant roles")
usernames = sorted(users_groups.keys())
matching_users = {}
roles = {}
arns = {}
x = 0
matched = set()
role_name_fmt = "role_name_{:03d}"
while x < len(usernames):
username = usernames[x]
if username in matched:
x += 1
continue
role = role_name_fmt.format(x)
lhs = users_groups[username]
for un_rhs in usernames[x:]:
if un_rhs == username:
continue
if users_eq(lhs, users_groups[un_rhs]):
if role not in matching_users:
roles[role] = users_groups[username]
arns[role] = set()
for group in users_groups[username]:
arns[role] |= groups_policies_arns[group]
arns[role] = sorted(arns[role])
matching_users[role] = set([username])
matched.add(username)
matched.add(un_rhs)
matching_users[role].add(un_rhs)
x += 1
roles_files_op = "{}_{}_user_roles.json".format(aws_name, aws_id)
open(roles_files_op, 'w').write(json.dumps({k: sorted(v) for k, v in roles.items() if len(v) > 0},indent=4))
arns_roles_op = "{}_{}_arn_roles.json".format(aws_name, aws_id)
open(arns_roles_op, 'w').write(json.dumps({k: sorted(v) for k, v in sorted(arns.items(), key=lambda x: x[0] ) if len(v) > 0},indent=4))
user_roles_op = "{}_{}_users.json".format(aws_name, aws_id)
open(user_roles_op, 'w').write(json.dumps({k: sorted(v) for k, v in matching_users.items() if len(v) > 0},indent=4))
admins = {}
for g, u in groups_users.items():
if g.find('Admin') > 0:
admins[g] = sorted(u)
admins_op = "{}_{}_admins.json".format(aws_name, aws_id)
open(admins_op, 'w').write(json.dumps(admins,indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment