Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible iam_user deletion does not work

I tried to delete an user by:

  - name: "Remove user abc"
    iam_user:
      name: abc
      state: absent

it gave me following error:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: DeleteConflictException: An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must delete access keys first.
fatal: [localhost]: FAILED! => {
    "changed": false, 
    "error": {
        "code": "DeleteConflict", 
        "message": "Cannot delete entity, must delete access keys first.", 
        "type": "Sender"
    }, 
    "response_metadata": {
        "http_headers": {
            "content-length": "298", 
            "content-type": "text/xml", 
            "date": "Thu, 12 Jul 2018 20:53:02 GMT", 
            "x-amzn-requestid": "91913df0-8615-11e8-b3e7-b16567885120"
        }, 
        "http_status_code": 409, 
        "request_id": "91913df0-8615-11e8-b3e7-b16567885120", 
        "retry_attempts": 0
    }
}

MSG:

Unable to delete user intelerad-billing-mzhao-client-creator-user: An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must delete access keys first.

It seems there is even no ansible module to delete access key.

any hints?

like image 353
Mike Zhao Avatar asked Jul 12 '18 20:07

Mike Zhao


1 Answers

AWS IAM APIs are finicky when it comes to user deletion. Deletion can be blocked if the user is assigned access keys or if the user's login profile doesn't exist.

Funny enough, Ansible has two modules that you can use to delete users: iam and iam_user, but one errors on access keys and the other errors on non-existant login profiles.

So let's go ahead and leverage AWS CLI for this one.

This playbook worked for me to create and delete a user with keys.

---
- name: Create / Delete IAM user with keys
  hosts: localhost
  connection: local

  vars:
    username: foo

  tasks:
    - name: Create user with keys
      iam:
        iam_type: user
        name: "{{ username }}"
        state: present
        access_key_state: create
        key_count: 2

    - name: Get all the access keys
      shell: aws iam list-access-keys --user-name {{ username }} --query 'AccessKeyMetadata[*].AccessKeyId'
      register: access_key_list

    - name: Delete each key
      shell: aws iam delete-access-key --access-key-id {{ item }} --user-name {{ username }}
      loop: "{{ access_key_list.stdout | from_json }}"

    - name: Delete user
      iam_user:
        name: "{{ username }}"
        state: absent

Note that the deletion task is iam_user. This is because plain iam will error if the user login profile doesn't exist.

Hope that helps!

like image 198
Himal Avatar answered Nov 15 '22 02:11

Himal