Skip to content

Instantly share code, notes, and snippets.

@tkalus
Last active September 17, 2023 08:17
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tkalus/e91c1d2d68bff68e9c6fa2b8ab2f5485 to your computer and use it in GitHub Desktop.
Save tkalus/e91c1d2d68bff68e9c6fa2b8ab2f5485 to your computer and use it in GitHub Desktop.
Delete an IAM User from an AWS Account
#!/usr/bin/env python3
"""
Delete an IAM User from an AWS Account.
Copyright (c) 2019 TKalus <tkalus@users.noreply.github.com>
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
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)
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
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}")
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)
#!/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 "${@}"
@thomasrlord
Copy link

Does this script work?

@tkalus
Copy link
Author

tkalus commented Nov 30, 2020

There is a gap in that it doesn't delete Signing Certs or Git Creds (details here), but it should work, yes.

@tkalus
Copy link
Author

tkalus commented Nov 30, 2020

Latest revision includes Signing Certs and Service-specific Creds along with moving from print() to logging-based output with more details.

@thomasrlord
Copy link

Just ran it and it worked to delete a user that was there, but when I input a user that doesn't exist I get:

"botocore.errorfactory.NoSuchEntityException: An error occurred (NoSuchEntity) when calling the GetUser operation: The user with name test-user cannot be found."

But I do see there is a:

if not user:
logger.error(f"User {user_name} does not exist")
return

I must be doing something wrong.

@tkalus
Copy link
Author

tkalus commented Dec 1, 2020

@thomasrlord, latest revision should fix the error case you were seeing; nice catch!

Problem was that user = iam.User(user_name) seems to only create a local reference to the IAM User (user will never be None) and it's not until the user's attributes are accessed, that an error is raised. I added .load() to force accessing the attributes, similar to how iam.LoginProfile(...) and friends are handled at lines 30-38.

@thomasrlord
Copy link

@tkalus

Just re-ran it. Looks like it's working!

When I ran it with a user that does not exist I now get:

"ERROR:delete_iam_user.py:User test-user does not exist"

I was in the process of creating a script like this myself (Getting my feet wet with python and boto3) and my approach was to use "list_users()" and then see if I could find the specified user in the list and return a true and false and go from there, but I was running into some quirks.

Thanks for being responsive and updating this code.

@bedge
Copy link

bedge commented Dec 24, 2020

Type annotations and all!! nice!
You going to do this for the rest of boto3 ? :)
Is there a license you associated? At my company "no license" == "can't use"
Very nice indeed. Thank you

@tkalus
Copy link
Author

tkalus commented Dec 24, 2020

@bedge Updated.

Type annotations and all!! nice!
You going to do this for the rest of boto3 ? :)

If I'm following what you're saying -- NOPE! ;-)

Is there a license you associated? At my company "no license" == "can't use"

For giggles -- sure! MIT Licensed.

Very nice indeed. Thank you

Thanks! Figured my hour-or-so of frustration isn't worth repeating ad nauseam for others.


I tossed in a cute little way to avoid having to pop a virtual env for a simple shell script -- mine, also MIT Licensed -- assuming you're on a POSIX-style machine with the AWS CLI installed in your path:

$ aws iam list-users | jq -r '.Users[]|.UserName'
$ ./delete_iam_user.sh [user_name]

@bedge
Copy link

bedge commented Jan 2, 2021

@tkalus Appreciate the license, makes it all nice and clean.

Regarding the user name iteration, I was attempting an all-python solution to wean myself of a bad habit of too much bash, so here's the additional wrapper I added around your delete method:

def get_group_users(session: boto3.session.Session, group: str) -> List[str]:
    iam = session.client("iam")
    group_users = []
    for user in iam.list_users()['Users']:
        user_name = user['UserName']
        user_groups = iam.list_groups_for_user(UserName=user_name)['Groups']
        if group in [group['GroupName'] for group in user_groups]:
            group_users.append(user_name)
    return group_users

Then, in main:
users = get_group_users(session, "bastion")
for user in users:
    delete_iam_user(session, user)

(I'm deleting all users in the bastion group, as created by aws-ec2-ssh)

Thanks again.

@tkalus
Copy link
Author

tkalus commented Jan 4, 2021

@bedge Nice!

One other way is to extend the reusability of the code is to handle it via an import:

delete_iam_users_in_group.py

#!/usr/bin/env python3
"""
Delete an IAM User from an AWS Account.

This is an untested example with minimal error handling -- the "AS IS" is for-reals.

Copyright (c) 2020 TKalus <tkalus@users.noreply.github.com>

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
from collections.abc import Iterable

import boto3.session

from delete_iam_user import delete_iam_user

logger = logging.getLogger(__name__)


def get_group_members(session: boto3.session.Session, group_name: str) -> Iterable[str]:
    """Get the user names of an IAM Group."""
    iam = session.resource("iam")
    group = iam.Group(group_name)
    try:
        group.load()
    except botocore.exceptions.ClientError as err:
        # If load failed with NoSuchEntity, IAM Group doesn't exist.
        if err.response.get("Error", {}).get("Code", "") == "NoSuchEntity":
            logger.error(f"Group {group_name} does not exist")
            return ""
        raise err
    for user in group.users.all():
        yield user.name


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()
    group_name = dict(enumerate(sys.argv)).get(1)
    for user_name in get_group_members(session, group_name):
        if user_name:
            delete_iam_user(session, user_name)

@bedge
Copy link

bedge commented Jan 4, 2021

@tkalus
The iterable is a nice touch too. Nice subtle reminder :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment