diff --git a/tasks/users.yaml b/tasks/users.yaml index 1f73eb1..3e558df 100644 --- a/tasks/users.yaml +++ b/tasks/users.yaml @@ -1,17 +1,74 @@ +- name: Check if the list of users from the previous run exists + ansible.builtin.stat: + path: "{{ system.prefix.sudoers }}/zz-ansible-users.list" + register: old_users + +- name: Handle the old users deletion + when: old_users.stat.exists + block: + - name: Fetch old users list + ansible.builtin.slurp: + path: "{{ system.prefix.sudoers }}/zz-ansible-users.list" + register: old_users_contents + + - name: Specify the users for deletion + ansible.builtin.set_fact: + old_users_var: "{{ old_users_contents.content | b64decode | from_json | difference(system.users) }}" + + - name: Fail if all users are about to be deleted + when: (old_users_var | length > 0) and (system.users | length == 0) + ansible.builtin.fail: + msg: | + system['users'] is empty, which means that you're about to delete ALL USERS on your target host + This is very dangerous and will most likely break your system. + + - name: Fail if the current Ansible user is about to get deleted + when: ansible_user in old_users_var + ansible.builtin.fail: + msg: | + User {{ ansible_user }} can not be removed, since it's being used to run the current Ansible playbook + Please run the playbook with a different user to remove the user {{ ansible_user }} + + - name: Remove old users + register: users_deleted + ansible.builtin.user: + name: "{{ item }}" + state: absent + force: yes + loop: "{{ old_users_var }}" + - name: Create groups - loop: "{{ system.groups|dict2items|list }}" + ansible.builtin.group: + name: "{{ item.key }}" + loop: "{{ system.groups | dict2items | list }}" loop_control: label: "{{ item.key }}" - group: - name: "{{ item.key }}" - name: Create users - loop: "{{ system.users|dict2items|list }}" - loop_control: - label: "{{ item.key }}" - user: + register: users_created + ansible.builtin.user: name: "{{ item.key }}" - comment: "{{ item.full_name|default(omit, true) }}" - groups: "{{ item.value.groups|default({}, true)|dict2items|selectattr('value', 'eq', true)|map(attribute='key')|list }}" + comment: "{{ item.full_name | default(omit, true) }}" + groups: >- + {{ + item.value.groups | + default({}, true) | + dict2items | + selectattr('value', 'eq', true) | + map(attribute='key') | + list + }} append: yes - shell: "{{ item.value.shell|default('/bin/bash', true) }}" + shell: "{{ item.value.shell | default('/bin/bash', true) }}" + loop: "{{ system.users | dict2items | list }}" + loop_control: + label: "{{ item.key }}" + +- name: Copy a list of current users to the target host + when: (users_deleted is defined and users_deleted.changed) or users_created.changed + ansible.builtin.copy: + dest: "{{ system.prefix.sudoers }}/zz-ansible-users.list" + owner: root + group: root + mode: 0644 + content: "{{ system.users }}"