Hey all,

I was surprised not to find an easy copy-pasteable script online for “how to delete AWS IAM roles & detach policies with AWS CLI in Bash”, so here’s my take. I’ve recently had to run a cleanup of some roles, so this is what I used.

roles=("RoleA" "RoleB" "RoleC")for role in ${roles[@]} ;
do
echo "Role $role"
role_attached_policies=$(aws iam list-attached-role-policies --role-name $role --query 'AttachedPolicies[*].PolicyArn' --output text)
for policy_arn in $role_attached_policies ;
do
aws iam detach-role-policy --role-name $role --policy-arn $policy_arn
done
role_inline_policies=$(aws iam list-role-policies --role-name $role --query 'PolicyNames' --output text)
for policy_name in $role_inline_policies ;
do
aws iam delete-role-policy --role-name $role --policy-name $policy_name
done

aws iam delete-role --role-name $role
done

--

--

Alexander Papageorgiou

Alexander Papageorgiou

Senior Cloud Engineer @ VanMoof. JVM (Java/Kotlin/Groovy) developer. Founded Thalatta, a SaaS startup https://twitter.com/alkoclick