delete-iam-user.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env python3
  2. """
  3. Delete an IAM User from an AWS Account.
  4. Copyright (c) 2019 TKalus <tkalus@users.noreply.github.com>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. this software and associated documentation files (the "Software"), to deal in
  7. the Software without restriction, including without limitation the rights to
  8. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. the Software, and to permit persons to whom the Software is furnished to do so,
  10. subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  15. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  16. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  17. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  18. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19. SOURCE: https://gist.github.com/tkalus/e91c1d2d68bff68e9c6fa2b8ab2f5485
  20. """
  21. import logging
  22. import sys
  23. import boto3.session
  24. import botocore.exceptions
  25. logger = logging.getLogger(__file__)
  26. def delete_iam_user(session: boto3.session.Session, user_name: str) -> None:
  27. """For a given boto3.session.Session, delete the IAM User and all assoc'd resources."""
  28. iam = session.resource("iam")
  29. iam_client = session.client("iam")
  30. user = iam.User(user_name)
  31. try:
  32. user.load()
  33. except botocore.exceptions.ClientError as err:
  34. # If load failed with NoSuchEntity, IAM User doesn't exist.
  35. if err.response.get("Error", {}).get("Code", "") == "NoSuchEntity":
  36. logger.error(f"User {user_name} does not exist")
  37. return
  38. raise err
  39. logger.debug(f"Deleting IAM User: {user.arn}")
  40. for group in user.groups.all():
  41. logger.debug(f"Removing {user.arn} from Group {group.arn}")
  42. user.remove_group(GroupName=group.name)
  43. try:
  44. login_profile = iam.LoginProfile(user.name)
  45. login_profile.load()
  46. logger.debug(f"Deleting Login Profile (I.E. Password) from {user.arn}")
  47. login_profile.delete()
  48. except botocore.exceptions.ClientError as err:
  49. # If load failed with NoSuchEntity, No Login Profile
  50. if err.response.get("Error", {}).get("Code", "") != "NoSuchEntity":
  51. raise err
  52. for device in user.mfa_devices.all():
  53. logger.debug(f"Removing MFA Device from {user.arn}: {device.serial_number}")
  54. device.disassociate()
  55. for access_key in user.access_keys.all():
  56. logger.debug(f"Deleting Access Key from {user.arn}: {access_key.access_key_id}")
  57. access_key.delete()
  58. for policy in user.policies.all():
  59. logger.debug(f"Deleting Inline Policy from {user.arn}: {policy.name}")
  60. policy.delete()
  61. for policy in user.attached_policies.all():
  62. logger.debug(f"Detatching Managed Policy from {user.arn}: {policy.arn}")
  63. user.detach_policy(PolicyArn=policy.arn)
  64. for cert in user.signing_certificates.all():
  65. logger.debug(f"Deleting Signing Cert from {user.arn}: {cert.id}")
  66. iam_client.delete_signing_certificate(UserName=user.name, CertificateId=cert.id)
  67. for ssh_public_key_id in [
  68. key.get("SSHPublicKeyId", "")
  69. for key in iam_client.list_ssh_public_keys(UserName=user.name).get(
  70. "SSHPublicKeys", []
  71. )
  72. ]:
  73. logger.debug(f"Deleting SSH Public Key from {user.arn}: {ssh_public_key_id}")
  74. iam_client.delete_ssh_public_key(
  75. UserName=user.name, SSHPublicKeyId=ssh_public_key_id
  76. )
  77. for service_name, service_specific_credential_id in {
  78. cred.get("ServiceName", ""): cred.get("ServiceSpecificCredentialId", "")
  79. for cred in iam_client.list_service_specific_credentials(
  80. UserName=user.name
  81. ).get("ServiceSpecificCredentials", [])
  82. }.items():
  83. logger.debug(
  84. f"Deleting Service Specific Cred from {user.arn}:"
  85. f" {service_name}:{service_specific_credential_id}"
  86. )
  87. iam_client.delete_service_specific_credential(
  88. UserName=user.name,
  89. ServiceSpecificCredentialId=service_specific_credential_id,
  90. )
  91. logger.info(f"Deleted IAM user: {user.name}")
  92. user.delete()
  93. if __name__ == "__main__":
  94. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  95. logging.getLogger("boto3").setLevel(logging.ERROR)
  96. logging.getLogger("botocore").setLevel(logging.ERROR)
  97. logging.getLogger("urllib3").setLevel(logging.ERROR)
  98. session = boto3.session.Session()
  99. user_name = dict(enumerate(sys.argv)).get(1)
  100. if user_name:
  101. delete_iam_user(session, user_name)