---
# SSH hardening is delivered as a drop-in under /etc/ssh/sshd_config.d/ rather than
# by editing the distro's sshd_config. The drop-in is validated before it is put in
# place, and a safety check refuses to disable password auth if no keys are deployed.

- name: Guard against lockout — refuse to disable password auth with no admin keys present
  ansible.builtin.assert:
    that:
      - linux_baseline_ssh_password_authentication | bool
        or (linux_baseline_admin_users | selectattr('authorized_keys', 'defined')
            | map(attribute='authorized_keys') | map('length') | select('>', 0) | list | length > 0)
    fail_msg: >-
      Refusing to disable SSH password authentication: no admin user has an
      authorized_keys entry, which would lock you out. Add a key or set
      linux_baseline_ssh_password_authentication: true.
    quiet: true
  when: not (linux_baseline_ssh_password_authentication | bool)

- name: Deploy the sshd hardening drop-in
  ansible.builtin.template:
    src: sshd_hardening.conf.j2
    dest: /etc/ssh/sshd_config.d/60-hardening.conf
    owner: root
    group: root
    mode: "0644"
    validate: "/usr/sbin/sshd -t -f %s"
  notify: Restart sshd
