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.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a task that creates multiple users with SSH keys from a list.BeginnerWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.Advanced