Last active
April 25, 2025 23:22
-
-
Save tkalus/e91c1d2d68bff68e9c6fa2b8ab2f5485 to your computer and use it in GitHub Desktop.
Revisions
-
tkalus revised this gist
Apr 25, 2025 . 2 changed files with 19 additions and 13 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -22,6 +22,17 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # PEP 723 - inline metadata # e.g. $ uv run delete_iam_user.py delete-me-user-name # # /// script # dependencies = [ # "boto3", # "boto3-stubs[iam]", # "botocore", # ] # /// import logging import sys @@ -63,12 +74,12 @@ def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: for access_key in user.access_keys.all(): logger.debug(f"Deleting Access Key from {user.arn}: {access_key.access_key_id}") access_key.delete() for inline_policy in user.policies.all(): logger.debug(f"Deleting Inline Policy from {user.arn}: {inline_policy.name}") inline_policy.delete() for attached_policy in user.attached_policies.all(): logger.debug(f"Detatching Managed Policy from {user.arn}: {attached_policy.arn}") user.detach_policy(PolicyArn=attached_policy.arn) for cert in user.signing_certificates.all(): logger.debug(f"Deleting Signing Cert from {user.arn}: {cert.id}") iam_client.delete_signing_certificate(UserName=user.name, CertificateId=cert.id) @@ -106,6 +117,6 @@ def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: logging.getLogger("botocore").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) session = boto3.session.Session() user_name: str = dict(enumerate(sys.argv)).get(1, "") if user_name: delete_iam_user(session=session, user_name=user_name) This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,5 +0,0 @@ -
tkalus revised this gist
Dec 24, 2020 . 2 changed files with 28 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,26 @@ #!/usr/bin/env python3 """ Delete an IAM User from an AWS Account. Copyright (c) 2019 TKalus <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import logging import sys @@ -87,4 +108,4 @@ def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: session = boto3.session.Session() user_name = dict(enumerate(sys.argv)).get(1) if user_name: delete_iam_user(session, user_name) This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,5 @@ #!/bin/bash # (ab)Use the AWS CLI's Python environment to execute scripts. # Avoid the need to install a virtual env for a single-command. AWS_CLI_PYTHON="$(command sed -n '/^#!/s/^#!\([^ ]*\).*$/\1/p' "$(command -v aws)")" "${AWS_CLI_PYTHON:-command python3}" ./delete_iam_user.py "${@}" -
tkalus revised this gist
Dec 1, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -18,7 +18,7 @@ def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: try: user.load() except botocore.exceptions.ClientError as err: # If load failed with NoSuchEntity, IAM User doesn't exist. if err.response.get("Error", {}).get("Code", "") == "NoSuchEntity": logger.error(f"User {user_name} does not exist") return -
tkalus revised this gist
Dec 1, 2020 . 1 changed file with 8 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -15,9 +15,14 @@ def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: iam = session.resource("iam") iam_client = session.client("iam") user = iam.User(user_name) try: user.load() except botocore.exceptions.ClientError as err: # If load failed with NoSuchEntity, No Login Profile if err.response.get("Error", {}).get("Code", "") == "NoSuchEntity": logger.error(f"User {user_name} does not exist") return raise err logger.debug(f"Deleting IAM User: {user.arn}") for group in user.groups.all(): logger.debug(f"Removing {user.arn} from Group {group.arn}") -
tkalus revised this gist
Nov 30, 2020 . 1 changed file with 54 additions and 22 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,53 +1,85 @@ #!/usr/bin/env python3 """Delete an IAM User from an AWS Account.""" import logging import sys import boto3.session import botocore.exceptions logger = logging.getLogger(__file__) def delete_iam_user(session: boto3.session.Session, user_name: str) -> None: """For a given boto3.session.Session, delete the IAM User and all assoc'd resources.""" iam = session.resource("iam") iam_client = session.client("iam") user = iam.User(user_name) if not user: logger.error(f"User {user_name} does not exist") return logger.debug(f"Deleting IAM User: {user.arn}") for group in user.groups.all(): logger.debug(f"Removing {user.arn} from Group {group.arn}") user.remove_group(GroupName=group.name) try: login_profile = iam.LoginProfile(user.name) login_profile.load() logger.debug(f"Deleting Login Profile (I.E. Password) from {user.arn}") login_profile.delete() except botocore.exceptions.ClientError as err: # If load failed with NoSuchEntity, No Login Profile if err.response.get("Error", {}).get("Code", "") != "NoSuchEntity": raise err for device in user.mfa_devices.all(): logger.debug(f"Removing MFA Device from {user.arn}: {device.serial_number}") device.disassociate() for access_key in user.access_keys.all(): logger.debug(f"Deleting Access Key from {user.arn}: {access_key.access_key_id}") access_key.delete() for policy in user.policies.all(): logger.debug(f"Deleting Inline Policy from {user.arn}: {policy.name}") policy.delete() for policy in user.attached_policies.all(): logger.debug(f"Detatching Managed Policy from {user.arn}: {policy.arn}") user.detach_policy(PolicyArn=policy.arn) for cert in user.signing_certificates.all(): logger.debug(f"Deleting Signing Cert from {user.arn}: {cert.id}") iam_client.delete_signing_certificate(UserName=user.name, CertificateId=cert.id) for ssh_public_key_id in [ key.get("SSHPublicKeyId", "") for key in iam_client.list_ssh_public_keys(UserName=user.name).get( "SSHPublicKeys", [] ) ]: logger.debug(f"Deleting SSH Public Key from {user.arn}: {ssh_public_key_id}") iam_client.delete_ssh_public_key( UserName=user.name, SSHPublicKeyId=ssh_public_key_id ) for service_name, service_specific_credential_id in { cred.get("ServiceName", ""): cred.get("ServiceSpecificCredentialId", "") for cred in iam_client.list_service_specific_credentials( UserName=user.name ).get("ServiceSpecificCredentials", []) }.items(): logger.debug( f"Deleting Service Specific Cred from {user.arn}:" f" {service_name}:{service_specific_credential_id}" ) iam_client.delete_service_specific_credential( UserName=user.name, ServiceSpecificCredentialId=service_specific_credential_id, ) logger.info(f"Deleted IAM user: {user.name}") user.delete() if __name__ == "__main__": logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) logging.getLogger("boto3").setLevel(logging.ERROR) logging.getLogger("botocore").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) session = boto3.session.Session() user_name = dict(enumerate(sys.argv)).get(1) if user_name: delete_iam_user(session, user_name) -
tkalus created this gist
Aug 17, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ #!/usr/bin/env python3 """Delete an IAM User from an AWS Account""" import sys from boto3.session import Session def delete_iam_user(session, user_name): """For a given boto3.session.Session, delete the IAM User""" iam = session.resource("iam") iam_client = session.client("iam") user = iam.User(user_name) if not user: print(f"User {user_name} does not exist") print(f"Removing IAM User: {user_name}") for group in user.groups.all(): print(f" Removing from Group {group.name}") user.remove_group(GroupName=group.name) try: login_profile = iam.LoginProfile(user.name) login_profile.load() print(" Deleting Login Profile (I.E. Password)") login_profile.delete() except ClientError: # If load failed, No Login Profile pass for device in user.mfa_devices.all(): print(f" Removing MFA Device: {device.serial_number}") device.disassociate() for access_key in user.access_keys.all(): print(f" Deleting Access Key: {access_key.access_key_id}") access_key.delete() for policy in user.policies.all(): print(f" Deleting Inline Policy: {policy.name}") policy.delete() for policy in user.attached_policies.all(): print(f" Detatching Managed Policy: {policy.arn}") user.detach_policy(PolicyArn=policy.arn) resp = iam_client.list_ssh_public_keys(UserName=user_name) for key_id in [i.get("SSHPublicKeyId") for i in resp.get("SSHPublicKeys", [])]: print(f" Deleting SSH Public Key: {key_id}") iam_client.delete_ssh_public_key(UserName=user_name, SSHPublicKeyId=key_id) print(f" Deleting user: {user.name}") user.delete() if __name__ == "__main__": session = Session() user_name = dict(enumerate(sys.argv)).get(1) if user_name: delete_iam_user(session, user_name)