user_policies_check.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import os
  2. import boto3
  3. iam = boto3.client('iam')
  4. def answer_no(x): return True if str(x).lower() in [
  5. '0', 'no', 'false'] else False
  6. def answer_yes(x): return True if str(x).lower() in [
  7. '1', 'yes', 'true'] else False
  8. def send_notifications(message):
  9. # TO DO
  10. return True
  11. def detach_policies(users):
  12. message_body = 'AGGRESSIVE is set to ' + os.environ['AGGRESSIVE'] \
  13. if ('AGGRESSIVE' in os.environ and answer_yes(os.environ['AGGRESSIVE'])) \
  14. else 'AGGRESSIVE mode is not active'
  15. print message_body
  16. for user, policies in users.iteritems():
  17. notification = 'Processing ' + user
  18. print notification
  19. message_body += notification + "\n"
  20. for policy in policies:
  21. notification = policy['PolicyName'] + \
  22. ' will be detached from the user'
  23. print notification
  24. message_body += notification + "\n"
  25. if ('DRY_RUN' not in os.environ or answer_no(os.environ['DRY_RUN'])) \
  26. and ('AGGRESSIVE' in os.environ and answer_yes(os.environ['AGGRESSIVE'])):
  27. iam.detach_user_policy(
  28. UserName=user, PolicyArn=policy['PolicyArn'])
  29. else:
  30. notification = 'AGREESIVE is not active or DRY_RUN is enabled, so the policy is not removed'
  31. print notification
  32. message_body += notification + "\n"
  33. if len(users) > 0 and ('DRY_RUN' not in os.environ or answer_no(os.environ['DRY_RUN'])):
  34. send_notifications(message_body)
  35. else:
  36. print 'DRY_RUN is active and/or nothing to do'
  37. def lambda_handler(event, context):
  38. users = iam.list_users()
  39. user_policies = {}
  40. for user in users['Users']:
  41. attached_policy_list = iam.list_attached_user_policies(
  42. UserName=user['UserName'])
  43. user_policy_list = iam.list_user_policies(UserName=user['UserName'])
  44. if len(attached_policy_list['AttachedPolicies']) > 0 \
  45. or len(user_policy_list['PolicyNames']) > 0:
  46. user_policies[user['UserName']] = attached_policy_list['AttachedPolicies'] + \
  47. user_policy_list['PolicyNames']
  48. detach_policies(user_policies)
  49. # if __name__ == "__main__":
  50. # event = 1
  51. # context = 1
  52. # lambda_handler(event, context)