Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Write a playbook that hardens SSH: no root login, no password auth.

IntermediateHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: all
  become: true
  tasks:
    - name: Harden sshd
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^#?{{ item.key }}\\s"
        line: "{{ item.key }} {{ item.value }}"
        validate: /usr/sbin/sshd -t -f %s
      loop:
        - { key: PermitRootLogin, value: "no" }
        - { key: PasswordAuthentication, value: "no" }
        - { key: MaxAuthTries, value: "3" }
      notify: Restart sshd

  handlers:
    - name: Restart sshd
      ansible.builtin.service: { name: ssh, state: restarted }   # "sshd" on RHEL

Key trick → The regexp matches commented-out defaults too, so the line is replaced, not duplicated. validate with sshd -t stops you from locking yourself out with a broken config.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks