Docs / Automation & IaC / How to Automate Server Hardening with Ansible

How to Automate Server Hardening with Ansible

By Admin · Mar 1, 2026 · Updated Apr 23, 2026 · 24 views · 1 min read

How to Automate Server Hardening with Ansible

Manually hardening each Breeze is error-prone and time-consuming. Ansible lets you codify your security baseline into repeatable playbooks that enforce consistent hardening across every server.

The Hardening Playbook

Create harden.yml to automate common security tasks:

---
- hosts: breezes
  become: true
  tasks:
    - name: Update all packages
      apt:
        upgrade: dist
        update_cache: yes

    - name: Install security tools
      apt:
        name: [fail2ban, ufw, unattended-upgrades]
        state: present

    - name: Disable root SSH login
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PermitRootLogin'
        line: 'PermitRootLogin no'
      notify: restart sshd

    - name: Enable UFW with default deny
      ufw:
        state: enabled
        policy: deny
        direction: incoming

    - name: Allow SSH through firewall
      ufw:
        rule: allow
        port: '22'
        proto: tcp

  handlers:
    - name: restart sshd
      service:
        name: sshd
        state: restarted

Running the Playbook

ansible-playbook -i inventory.ini harden.yml

Additional Hardening Steps

  • Set SSH MaxAuthTries 3 and PasswordAuthentication no
  • Configure fail2ban jails for SSH brute-force protection
  • Enable automatic security updates with unattended-upgrades
  • Set proper file permissions on sensitive directories

Run this playbook on every new Breeze immediately after provisioning to ensure a secure baseline.

Was this article helpful?