Last active
April 20, 2022 08:05
-
-
Save varunchandak/51c71c82eebb2b7d12ab6cfa082a53bc to your computer and use it in GitHub Desktop.
delete unused aws iam roles using aws cli
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 characters
#!/bin/bash | |
aws iam list-roles --max-items 1000 | jq -r '.Roles[]|[.RoleName, .Arn, .CreateDate]|@csv' | grep -v -e '/aws-service-role/' -e '"AWSServiceRoleFor' -e '/aws-reserved/' | tr -d '"' | cut -d, -f1 | while read ROLE_NAME; do | |
echo "$ROLE_NAME" | |
aws iam get-role --role-name "$ROLE_NAME" | jq -r '.Role|.CreateDate, .RoleLastUsed.LastUsedDate // "UNUSED"' | |
done | paste -d, - - - | grep ",UNUSED$" | cut -d, -f1 | while read UNUSED_ROLE_NAME; do | |
echo "$UNUSED_ROLE_NAME is unused" | |
aws iam list-attached-role-policies --role-name "$UNUSED_ROLE_NAME" | jq -r '.AttachedPolicies[].PolicyArn' | while read ATTACHED_POLICY; do | |
aws iam detach-role-policy --role-name "$UNUSED_ROLE_NAME" --policy-arn "$ATTACHED_POLICY" | |
done | |
aws iam list-instance-profiles-for-role --role-name "$UNUSED_ROLE_NAME" | jq -r '.InstanceProfiles[].InstanceProfileName' | while read INSTANCE_PROFILE; do | |
aws iam remove-role-from-instance-profile --instance-profile-name "$INSTANCE_PROFILE" --role-name "$UNUSED_ROLE_NAME" | |
aws iam delete-instance-profile --instance-profile-name "$INSTANCE_PROFILE" | |
done | |
aws iam delete-role --role-name "$UNUSED_ROLE_NAME" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment