automationansibleuser-accountsrhel6

Using Ansible to remove multiple Unix accounts


I have written the below ansible code for removal of Unix user accounts.

  - hosts: dev
    vars:
    username: 'testuser'
    become: true
    tasks:
    - name: Remove User
      user:
       name: '{{ username }}'
       state: absent
       remove: yes

This works fine for a single user. However if I want to remove multiple users at the same time , do I need to create separate variable for each of the user to be deleted and a separate user resource to remove this user. In that case if there are mulitple users the code will become too long. ANy suggestions ?


Solution

  • Create a list of users to be deleted user_names. Then iterate the list by loop.

    - hosts: dev
      become: true
      vars:
        user_names:
          - testuser1
          - testuser2
          - testuser3
      tasks:
        - name: Remove Users
          user:
            name: "{{ item }}"
            state: absent
            remove: true
          loop: "{{ user_names }}"