---
- block:
    - name: Ensure that the sshd_config file has desired options
      blockinfile:
        dest: /etc/ssh/sshd_config
        marker: '# {mark} ANSIBLE MANAGED BLOCK ssh_tunneling_role'
        block: |
          Match Group algo
              AllowTcpForwarding local
              AllowAgentForwarding no
              AllowStreamLocalForwarding no
              PermitTunnel no
              X11Forwarding no
      notify:
        - restart ssh

    - name: Ensure that the algo group exist
      group: name=algo state=present

    - name: Ensure that the jail directory exist
      file:
        path: /var/jail/
        state: directory
        mode: 0755
        owner: root
        group: "{{ root_group|default('root') }}"

    - name: Ensure that the SSH users exist
      user:
        name: "{{ item }}"
        groups: algo
        home: '/var/jail/{{ item }}'
        createhome: yes
        generate_ssh_key: false
        shell: /bin/false
        state: present
        append: yes
      with_items: "{{ users }}"
      tags: update-users

    - name: The authorized keys file created
      authorized_key:
        user: "{{ item }}"
        key: "{{ lookup('file', 'configs/' + IP_subject_alt_name + '/pki/public/' + item + '.pub') }}"
        state: present
        manage_dir: true
        exclusive: true
      with_items: "{{ users }}"
      tags: update-users

    - name: Generate SSH fingerprints
      shell: ssh-keyscan {{ IP_subject_alt_name }} 2>/dev/null
      register: ssh_fingerprints

    - name: Fetch the known_hosts file
      local_action:
        module: template
        src: known_hosts.j2
        dest: configs/{{ IP_subject_alt_name }}/known_hosts
      become: no

    - name: Build the client ssh config
      local_action:
        module: template
        src: ssh_config.j2
        dest: configs/{{ IP_subject_alt_name }}/{{ item }}.ssh_config
        mode: 0600
      become: false
      tags: update-users
      with_items: "{{ users }}"

    - name: Get active users
      getent:
        database: group
        key: algo
        split: ':'
      tags: update-users

    - name: Delete non-existing users
      user:
        name: "{{ item }}"
        state: absent
        remove: yes
        force: yes
      when: item not in users
      with_items: "{{ getent_group['algo'][2].split(',') }}"
      tags: update-users
  rescue:
    - debug: var=fail_hint
      tags: always
    - fail:
      tags: always
