---

- name: Deploy sshd configuration
  template: src=sshd_config.j2 dest=/etc/ssh/sshd_config
  notify: restart sshd
  tags: ssh

- name: Create top level authorized keys directory
  file: path=/etc/ssh/authorized_keys/ state=directory mode=755 owner=root group=root
  tags: ssh

- name: Create an SSH key pair for root
  user:
    name: root
    generate_ssh_key: yes
    ssh_key_file: .ssh/id_rsa
  tags: ssh

- name: Create ssh users
  user:
    name: "{{ item.name }}"
  loop: "{{ ssh_users }}"
  register: ssh_create_user
  when: item.create_user | default(False)
  tags: ssh

- name: Check if sssd is installed
  stat: path=/usr/sbin/sss_cache
  register: ssh_sss_cache
  tags: ssh

  # Flush sss cache so we can modify newly available users
- name: Reset sss cache
  command: sss_cache -E
  when: ssh_sss_cache.stat.exists and ssh_create_user.results | selectattr('changed','equalto',True) | list | length > 0
  tags: ssh

  # We do this in two times (first create, then set shell and comment)
  # to prevent hitting a bug in ansible where usermod could be called before useradd
  # See https://github.com/ansible/ansible/issues/22576
- name: Set ssh user attributes
  user:
    name: "{{ item.name }}"
    comment: "{{ item.full_name | default(omit) }}"
    shell: "{{ item.shell | default(omit) }}"
  loop: "{{ ssh_users }}"
  when: item.create_user | default(False)
  tags: ssh

- name: Create private dir for Authorized keys
  file: path=/etc/ssh/authorized_keys/{{ item.name }} state=directory mode=700 owner={{ item.name }}
  ignore_errors: True # Needed eg, if LDAP isn't available on first run
  loop: "{{ ssh_users | rejectattr('keys_file', 'defined') | list }}"
  tags: ssh

- name: Deploy ssh user keys
  authorized_key:
    user: "{{ item.name }}"
    key: "{{ item.ssh_keys | default([]) | flatten | join(\"\n\") }}"
    key_options: "{{ item.key_options | default([]) | join(',') }}"
    path: "{{ item.keys_file | default('/etc/ssh/authorized_keys/' ~ item.name ~ '/authorized_keys') }}"
    manage_dir: False
    exclusive: "{{ item.keys_exclusive | default(True) }}"
  ignore_errors: True # Needed eg, if LDAP isn't available on first run
  loop: "{{ ssh_users }}"
  tags: ssh

- name: Ensure permissions and ownership on authorized_keys files
  file:
    path: /etc/ssh/authorized_keys/{{ item.name }}/authorized_keys
    mode: 0600
    owner: "{{ item.name }}"
  when: item.ssh_keys is defined
  ignore_errors: True
  loop: "{{ ssh_users | rejectattr('keys_file', 'defined') | list }}"
  tags: ssh

- name: Deploy sudo fragment
  template: src=sudo.j2 dest=/etc/sudoers.d/ssh_users mode=600
  tags: ssh
