Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash script to delete IAM users using AWS cli tool
#!/bin/bash
user=$1
echo "User: $user"
user_policies=$(aws iam list-user-policies --user-name $user --query 'PolicyNames[*]' --output text)
echo "Deleting user policies: $user_policies"
for policy in $user_policies ;
do
echo "aws iam delete-user-policy --user-name $user --policy-name $policy"
aws iam delete-user-policy --user-name $user --policy-name $policy
done
user_attached_policies=$(aws iam list-attached-user-policies --user-name $user --query 'AttachedPolicies[*].PolicyArn' --output text)
echo "Detaching user attached policies: $user_attached_policies"
for policy_arn in $user_attached_policies ;
do
echo "aws iam detach-user-policy --user-name $user --policy-arn $policy_arn"
aws iam detach-user-policy --user-name $user --policy-arn $policy_arn
done
user_groups=$(aws iam list-groups-for-user --user-name $user --query 'Groups[*].GroupName' --output text)
echo "Detaching user attached group: $user_groups"
for group in $user_groups ;
do
echo "aws iam remove-user-from-group --user-name $user --group-name $group"
aws iam remove-user-from-group --user-name $user --group-name $group
done
user_access_keys=$(aws iam list-access-keys --user-name $user --query 'AccessKeyMetadata[*].AccessKeyId' --output text)
echo "Deleting user access keys: $user_accces_keys"
for key in $user_access_keys ;
do
echo "aws iam delete-access-key --user-name $user --access-key-id $key"
aws iam delete-access-key --user-name $user --access-key-id $key
done
echo "Deleting user login profile"
echo "aws iam delete-login-profile --user-name $user"
aws iam delete-login-profile --user-name $user
echo "Deleting user: $user"
echo "aws iam delete-user --user-name $user"
aws iam delete-user --user-name $user
@OliverGoetz

This comment has been minimized.

Copy link

@OliverGoetz OliverGoetz commented Oct 22, 2021

Very useful, thanks for sharing this!

Just two observations:

  1. There's a typo in line 35: should be $user_access_keys instead of $user_accces_keys
  2. If the user has MFA devices configured it cannot be deleted in the end. The MFA devices need to be deactivated first. I'm not sure how the text output looks when there is more than one such device, as the documentation always only shows the json output format.

The command to list the MFA devices is aws iam list-mfa-devices --user $user.
The command to deactivate an MFA device is aws iam deactivate-mfa-device --user $user --serial-number $device_id

I will probably rewrite this to use the json output as I find it's easier and more stable to parse if you have something like jq installed.

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