# Everything in main indentation has a separate ssh connection; for better perf. put everything inside the tasks section of one block
- name: Main playbook
  hosts: all
  vars_files:
    # Ansible Vault
    - ./secret_vars.yaml
  vars:
    # Local variables for use in user-creation
    users:
      - { name: 'testuser1', pass: "{{testuser1_pass}}", groups: 'users' }
      - { name: 'testuser2', pass: "{{testuser2_pass}}", groups: 'users' }
      - { name: 'ansiblerunner', pass: "{{ansiblerunner_pass}}", groups: 'users,sudo' }
  tasks:
    - name: Std Repo stuff
      ansible.builtin.apt:
        # apt update before installing
        update_cache: true
        name:
          - vim
          - curl
          - sudo
          - python3-pip
          - python3-passlib # needed for user password
          - vnstat
          - tmux
    - name: Enable VNStat service
      ansible.builtin.service:
        name: vnstat
        enabled: true
        # Enable + Start
        state: started
    - name: "Allow admin users to sudo without a password"
      ansible.builtin.lineinfile:
        path: "/etc/sudoers"
        state: "present"
        # If not found it will be inserted at end of file
        regexp: "^%sudo" # A regex that matches all lines that start with %sudo
        line: "%sudo ALL=(ALL) NOPASSWD: ALL"
        validate: /usr/sbin/visudo -cf %s # Revert if visudo says the syntax is wrong
    - name: Add user
      ansible.builtin.user:
        name: "{{ item.name }}"
        group: users # Primary group
        groups: "{{ item.groups }}"
        password: "{{ item.pass | password_hash('sha512') }}"
        shell: /bin/bash
        update_password: on_create # Add the same initial password for all users (can be overwritten by user)
      with_items:
        - "{{ users }}"
    - name: "Add authorized keys"
      ansible.posix.authorized_key:
        user: "{{ item.name }}"
        key: "{{ lookup('file', 'files/' + item.name + '.pub') }}"
      with_items:
        - "{{ users }}"
    - name: Sshd configuration file update
      ansible.builtin.template:
        src: sshd_config.j2
        dest: /etc/ssh/sshd_config
        backup: true # creates a backup of original file on the node
        owner: 0
        group: 0
        mode: "0644"
        validate: "/usr/sbin/sshd -T -f %s"
      notify:
        # Notify-Handlers allow certain extra tasks to be executed on the success of current task
        - Restart sshd
  handlers:
    - name: Restart sshd
      ansible.builtin.service:
        name: ssh
        enabled: true
        state: restarted
