---
# Script to delete a user from the servers
#
# To run the script:
# ansible-playbook -K remove_user.yml -i hosts-xxx -e 'target=targethost login=username'
# ansible-playbook -K remove_user.yml -i hosts-xxx -e 'target=targethost login=username' --limit=*.mydomain.com
#

- name: Create user on target system(s)
  hosts: '{{target}}'
  become: yes
  become_user: root
  tasks:
  - name: Remove system user
    user:
      name: '{{ login }}'
      state: absent

  - name: Remove user from SSH conf
    lineinfile:
      path: /etc/ssh/sshd_config.d/sellyoursaas.conf
      line: "AllowUsers {{ login }}"
      state: absent
    register: removelineinsshconf

  - name: Remove user from SSH conf
    lineinfile:
      path: /etc/ssh/sshd_config.d/sellyoursaas-users.conf
      line: "AllowUsers {{ login }}"
      state: absent
    register: removelineinsshconf2

  - name: Restart SSH service to flush that user from in-memory configuration
    service:
      name: ssh
      state: restarted
    when: removelineinsshconf.changed|removelineinsshconf2.changed

  - name: Remove IP file from sellyoursaas.d
    ansible.builtin.file:
      path: "/etc/sellyoursaas.d/{{ login }}-allowed-ip.conf"
      state: absent
