I have created an IAM group via terraform using the following code snippet. Later I manually assigned users to this group depending on demands – therefore these group associations are managed outside terraform.
resource "aws_iam_group" "eks_user" {
name = "eks_user"
path = "/eks/user/"
force_destroy = true
}
Now I want to delete the group using terraform destroy
to save costs at the end of the day, but it fails as the group still has users assigned. How can I still delete resources even they have associations?
...
module.main.module.vpc.module.vpc.aws_vpc.this[0]: Destruction complete after 0s
module.main.module.eks.module.eks.aws_iam_role.cluster[0]: Destruction complete after 2s
╷
│ Error: Error deleting IAM Group eks_user: DeleteConflict: Cannot delete entity, must remove users from group first.
│ status code: 409, request id: 479d0bfb-b099-4d4a-9753-d1c7601d142e
│
│
╵
You can use the AWS CLI to remove those users:
remove-user-from-group
https://docs.aws.amazon.com/cli/latest/reference/iam/remove-user-from-group.html
And on Terraform you can use a null resource to do the removal when you call destroy,
something like:
resource "null_resource" "remove_users" {
depends_on = ["aws_iam_group.your_group"]
provisioner "local-exec" {
when = "destroy"
command = "aws iam remove-user-from-group --user-name Bob --group-name Admins"
}
}
of course that is a very simple command ...
you probably will need multiple of those removals or a loop to remove all
Now if you are exclusively doing this to reduce costs,
you might not need to do this, seem the AWS Groups are free
https://aws.amazon.com/iam/faqs/
Any AWS customer can use IAM. The service is offered at no additional charge. You will be charged only for the use of other AWS services by your users.