--- - name: Work out what the SSH service is called here ansible.builtin.set_fact: ssh_hardening_service_name: "{{ 'sshd' if ansible_facts['os_family'] == 'RedHat' else 'ssh' }}" - name: Check the connecting account has a key when: ssh_hardening_require_key_present | bool block: # become: false and a ~ path, so this checks the account Ansible logs in # as. Facts are gathered as root, so a path built from them would not. - name: Look for authorized_keys ansible.builtin.stat: path: "~/.ssh/authorized_keys" become: false register: ssh_hardening_authorized_keys - name: Stop if there is none ansible.builtin.assert: that: - ssh_hardening_authorized_keys.stat.exists - ssh_hardening_authorized_keys.stat.size > 0 fail_msg: >- {{ inventory_hostname }} has no authorized_keys for {{ ansible_user | default('the account Ansible connects as') }}. Install a key first, or set ssh_hardening_require_key_present to false if keys come from certificates or you have console access. - name: Make sure the drop-in directory exists ansible.builtin.file: path: "{{ ssh_hardening_dropin_path | dirname }}" state: directory owner: root group: root mode: "0755" # Without this line the drop-in file is read by nobody, and the run reports # success while changing nothing at all. - name: Make sure the main config reads the drop-in directory ansible.builtin.lineinfile: path: /etc/ssh/sshd_config line: "Include {{ ssh_hardening_dropin_path | dirname }}/*.conf" insertbefore: BOF state: present validate: /usr/sbin/sshd -t -f %s notify: Reload sshd - name: Write the hardening settings ansible.builtin.template: src: hardening.conf.j2 dest: "{{ ssh_hardening_dropin_path }}" owner: root group: root mode: "0600" validate: /usr/sbin/sshd -t -f %s notify: Reload sshd - name: Make sure sshd is enabled and running ansible.builtin.service: name: "{{ ssh_hardening_service_name }}" enabled: true state: started # Proves the result by reading it back. Runs every time, costs nothing, and # fails loudly if some later change quietly turns passwords back on. - name: Read back the settings the server will actually use ansible.builtin.command: /usr/sbin/sshd -T changed_when: false register: ssh_hardening_effective - name: Confirm password logins are off ansible.builtin.assert: that: - "'passwordauthentication no' in ssh_hardening_effective.stdout | lower" fail_msg: >- sshd still accepts passwords. Another file is setting it first. Check {{ ssh_hardening_dropin_path | dirname }} for a file that sorts before {{ ssh_hardening_dropin_path | basename }}. success_msg: "Key-only logins confirmed."