A server baseline written as a runbook is a document nobody trusts to re-run. Written as an Ansible role, it becomes something you can apply to one box or a hundred, on Tuesday and again on Friday, and know that the second run changes nothing.
Most “server hardening” guides are a wall of shell commands you paste once and never touch again. Six months later nobody knows whether the box still matches the guide, because the guide was never a source of truth — it was a one-time ritual. The point of expressing a baseline in Ansible is not automation for its own sake. It is that the playbook becomes the stated configuration, re-running it is the check, and drift shows up as changed tasks. That is a change-governance property, not just a convenience.
This builds one baseline role for Ubuntu 24.04 on Ansible 9 (ansible-core 2.16). It manages admin users and their keys, hardens sshd through a validated drop-in, sets a default-deny firewall, turns on unattended security upgrades and keeps the clock honest with chrony — all idempotent, so a clean second run reports zero changes.
Free · 4 minutes
Is your engineering team shipping safely, or quietly accumulating risk?
Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.
Idempotency is the whole point
An idempotent task describes the state you want, not the command you would type. ansible.builtin.apt with state: present installs a package only if it is missing. ansible.builtin.user creates an account only if it differs from the declared one. The trap is reaching for ansible.builtin.command or shell, which run every time and report changed every time, because Ansible cannot see inside them. If you find yourself shelling out, you have usually missed the module that already models that state. The same discipline that makes a CIS-aligned baseline verifiable rather than merely applied is what makes an Ansible run trustworthy: the apply and the check are the same action.
Lay the role out the conventional way: roles/baseline/ with tasks/, handlers/, templates/ and defaults/main.yml. The firewall module lives in a collection, so declare your dependencies rather than assuming them:
# requirements.yml — install with: ansible-galaxy collection install -r requirements.yml
collections:
- name: community.general
version: ">=8.0.0"
The role, top to bottom
Here is roles/baseline/tasks/main.yml. Every task names the state it wants; none of it shells out. The variables (admin_users, ssh_port) belong in defaults/main.yml or group_vars so the same role serves different fleets from one inventory.
---
# roles/baseline/tasks/main.yml
- name: Ensure admin users exist
ansible.builtin.user:
name: "{{ item.name }}"
groups: sudo
append: true
shell: /bin/bash
state: present
loop: "{{ admin_users }}"
loop_control:
label: "{{ item.name }}"
- name: Install each admin user's authorised key
ansible.posix.authorized_key:
user: "{{ item.name }}"
key: "{{ item.key }}"
state: present
exclusive: true
loop: "{{ admin_users }}"
loop_control:
label: "{{ item.name }}"
- name: Deploy hardened sshd drop-in (validated before it is written)
ansible.builtin.template:
src: 99-hardening.conf.j2
dest: /etc/ssh/sshd_config.d/99-hardening.conf
owner: root
group: root
mode: "0644"
validate: "/usr/sbin/sshd -t -f %s"
notify: Reload ssh
- name: Install baseline packages
ansible.builtin.apt:
name:
- ufw
- unattended-upgrades
- chrony
state: present
update_cache: true
cache_valid_time: 3600
- name: Allow SSH through the firewall before enabling it
community.general.ufw:
rule: allow
port: "{{ ssh_port | default('22') }}"
proto: tcp
- name: Set default-deny inbound and enable ufw
community.general.ufw:
state: enabled
direction: incoming
policy: deny
- name: Enable unattended security upgrades
ansible.builtin.template:
src: 20auto-upgrades.j2
dest: /etc/apt/apt.conf.d/20auto-upgrades
owner: root
group: root
mode: "0644"
- name: Ensure chrony is running and enabled at boot
ansible.builtin.service:
name: chrony
state: started
enabled: true
Two ordering points earn their place. The firewall allow rule runs before state: enabled, so you never lock yourself out of the box you are configuring — a mistake that turns a routine apply into a data-centre visit. And the authorized_key task runs before SSH is hardened to key-only, so the keys are in place before password login is removed.
Validate before you write, reload only on change
The validate parameter is the safety catch. Ansible writes the template to a temporary file, runs sshd -t -f against it, and only moves it into place if the syntax check passes. A typo in the drop-in never reaches /etc/ssh/, so a bad edit cannot leave you with an sshd that refuses to start. The %s is substituted with that temporary path.
The template itself is a drop-in, which is the idiomatic approach on 24.04 — the shipped sshd_config already ends with Include /etc/ssh/sshd_config.d/*.conf, so you never edit the main file:
# roles/baseline/templates/99-hardening.conf.j2
Port {{ ssh_port | default('22') }}
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
X11Forwarding no
MaxAuthTries 3
# roles/baseline/templates/20auto-upgrades.j2
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
The notify: Reload ssh line is what keeps the run quiet on repeat. A handler fires only when its task actually reports changed, and it runs once at the end of the play no matter how many tasks notified it. So the service is reloaded when the drop-in changes and left untouched when it does not — no needless restarts on every apply. handlers/main.yml:
---
# roles/baseline/handlers/main.yml
- name: Reload ssh
ansible.builtin.service:
name: ssh
state: reloaded
Reload, not restart: reloading sshd re-reads its configuration without dropping your current session, so applying the baseline over SSH does not kill the connection running it.
Lint it, dry-run it, then target the fleet
Before a first apply, two cheap checks catch most of what goes wrong. ansible-lint flags the anti-patterns that break idempotency — unnamed tasks, bare command where a module exists, missing changed_when. Install it into its own isolated environment rather than polluting the system Python; pipx is the sane way to install a Python CLI tool. Then run the play in check mode, which reports what would change without touching the host:
# Lint the role
ansible-lint roles/baseline
# Dry run against the fleet, showing the diffs it would apply
ansible-playbook -i inventory.ini site.yml --check --diff
# Apply for real
ansible-playbook -i inventory.ini site.yml
# The test that matters: run it again, expect changed=0
ansible-playbook -i inventory.ini site.yml
The inventory is where one role becomes a fleet control. Group your hosts, apply defaults per group, and the same baseline lands on every box with the differences held in data rather than duplicated in tasks:
# inventory.ini
[web]
web01.example.internal
web02.example.internal
[db]
db01.example.internal
[all:vars]
ansible_user=deploy
The honest measure of this role is the second run. A first apply on a fresh host reports a screenful of changes; that is expected. Run the identical play a second time and every task should read ok, with changed=0 in the recap. If it does not, one of your tasks is lying about state — usually a command that should have been a module, or a template whose whitespace shifts between renders. Fix that before you scale it out, because a baseline that reports phantom changes is a baseline nobody will trust enough to run. The same principle carries across the rest of the estate, from a Windows Server 2022 first-hardening pass to the smaller decisions like how a Linux host handles swap: the config you can re-run without fear is the config you actually know the state of.
A runbook tells you what someone once did. A green, idempotent playbook tells you what every server is, right now, and lets you prove it on demand. That is the difference a supervisor, or your own on-call self at 3am, will care about.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.