--- - name: Harden SSH Configuration hosts: all become: true vars: # Set this to true in Semaphore to allow key-based root login # If ALLOW_ROOT_SSH isn't in Semaphore, it defaults to 'false' allow_root_ssh: "{{ ALLOW_ROOT__SSH | default(false) | bool }}" tasks: - name: Backup SSH config ansible.builtin.copy: src: /etc/ssh/sshd_config dest: /etc/ssh/sshd_config.bak remote_src: true mode: '0600' - name: Configure SSH Hardening ansible.builtin.lineinfile: path: /etc/ssh/sshd_config regexp: "{{ item.regexp }}" line: "{{ item.line }}" state: present validate: '/usr/sbin/sshd -t -f %s' loop: # Disables all password logins - { regexp: '^#?PasswordAuthentication', line: "PasswordAuthentication no" } # Allows root ONLY if they have a key - { regexp: '^#?PermitRootLogin', line: "PermitRootLogin {{ 'prohibit-password' if allow_root_ssh else 'no' }}" } # Ensures PubKey is definitely on - { regexp: '^#?PubkeyAuthentication', line: "PubkeyAuthentication yes" } notify: Restart SSH handlers: - name: Restart SSH ansible.builtin.service: name: ssh state: restarted