---

- name: create users
  hosts: ansible-development
  become: true

  vars:
    users:
      - exampleuser

  tasks:
  - name: "Create user accounts and add users to groups"
    user:
      name: "{{ item }}"
      password: "{{ item }}"
      groups: "sudo"
      shell: "/bin/bash"
    with_items: "{{ users }}"

  - name: "Add authorized keys"
    authorized_key:
      user: "{{ item }}"
      key: "{{ lookup('file', 'files/'+ item + '.key.pub') }}"
    with_items: "{{ users }}"

  - name: "Add User to AllowUsers"
    replace:
      dest: "/etc/ssh/sshd_config"
      regexp: '^(AllowUsers(?!.*\b{{ item }}\b).*)$'
      replace: '\1 {{ item }}'
    with_items: "{{ users }}"
    register: sshd_changes

  - name: "Restart sshd"
    service:
      name: "ssh"
      state: "restarted"
    when: sshd_changes.changed

  - name: "Restart monit"
    service:
      name: "monit"
      state: "restarted"
    when: sshd_changes.changed
