amazon-iamamazon-policy

How to delete an iam policy with multiple versions on the command line with one command?


I am trying to delete a policy with multiple versions of the command line like so:

function iam-list-versions () {
  aws iam list-policy-versions --query "Versions[].VersionId" --policy-arn $1 --output text 
}

function iam-delete-policy-versions () {
  iam-list-versions $1 | xargs -n 1 -I{} aws iam delete-policy-version --policy-arn $1 --version-id {}
}

function iam-delete-policy () {
  iam-delete-policy-versions $1
  aws iam delete-policy --policy-arn $1
}

And then run iam-delete-policy arn:aws:iam::123456789012:policy/... But I keep getting the error:

An error occurred (DeleteConflict) when calling the DeletePolicyVersion operation: Cannot delete the default version of a policy.

An error occurred (DeleteConflict) when calling the DeletePolicy operation: This policy has more than one version. Before you delete a policy, you must delete the policy's versions. The default version is deleted with the policy.

Looks like my iam-delete-policy-versions function is not working. Wish they would simply add a --force flag.


Solution

  • The error messages are suggesting that:

    I also notice that list-policy-versions returns a field called IsDefaultVersion that indicates whether a policy is the default version.

    Therefore, you would need to do something like:

    This would probably be easier in a Python script.