Detecting configuration drift with Ansible check mode
In Making Linux host tuning repeatable with Ansible the last few sections said: run the same play in check mode on a schedule, and it becomes a drift detector. That was one paragraph. This post is the longer version: how to set it up so the output means something, and what it can’t see.
I use Ansible for configuration management, with the inventory grouped by environment (prd, stg, dev) and changes promoted dev → stg → prd. The examples assume that layout.
1. What drift looks like
Drift is any difference between what the code says and what is on the host. It usually comes from one of these:
- Someone fixed an incident by hand and never put the fix back in the repo.
- A package update rewrote a config file or re-enabled a service.
- A host was rebuilt from an older image.
- A change went to dev and stg but never made it to prd, or the other way round.
None of these break anything on the day. They break the next change, because the play you tested in stg now hits a prd host that isn’t in the state you assumed. Or they show up as a host that behaves a bit differently from its neighbours, and you spend an afternoon finding out why.
You want to find drift on a quiet Tuesday, not during a rollout.
2. What check mode actually does
--check runs the play without making changes. Modules that support check mode report what they would change. --diff adds a before/after view for modules that support it, mostly the file ones: template, copy, lineinfile.
ansible-playbook -i inventory/hosts.yml site.yml \
--limit prd --check --diff
If the code and the host agree, every task comes back ok. If a file was edited by hand, the task comes back changed and the diff shows the lines. That’s the whole idea.
The part that matters for drift detection is what the Ansible docs say next: modules that do not support check mode report nothing and do nothing. So a clean check run means “nothing drifted that check mode can see”. Which brings us to the gaps.
3. The gaps
command and shell don’t run. The command module’s check mode support is listed as partial: the command itself is arbitrary, so Ansible can’t predict what it would do. In check mode these tasks are skipped, unless you use creates or removes, which let Ansible decide from a file’s presence. See the command module docs and the shell module docs.
That has two effects:
- Anything the play does through
commandis invisible to the drift check. - Any later task that uses the registered result of a skipped command has nothing to work with, and may fail or take the wrong branch.
Some modules don’t support check mode at all. Each module’s docs page has an “Attributes” table with a check_mode row: full, partial or none. If a task you care about uses a module with “none”, it won’t show up.
Only managed things are checked. If a setting isn’t in the play, Ansible doesn’t know about it. Someone adding a new sysctl file by hand won’t show up unless something in your play owns that directory or reads that value.
Runtime state isn’t config. A sysctl task with sysctl_set: true compares the live value too, which is good. But a file can be correct while the running process still has the old config loaded, because nobody restarted it. Check mode won’t tell you about that unless you read the live state yourself.
4. Making command tasks honest
Most plays have a few command tasks that only read state, like tuned-adm active in the tuning role. For those, tell Ansible two things: run this even in check mode, and it never changes anything.
- name: Get active tuned profile
ansible.builtin.command: tuned-adm active
register: tuned_active
changed_when: false
check_mode: false
check_mode: false forces the task to run normally even under --check. Only do this for tasks that are genuinely read-only. check_mode: false on a task that writes something means your “dry run” writes something.
changed_when: false stops it reporting changed on every run. Without it, every read-only command adds noise to the recap, and “changed > 0” stops meaning anything.
For command tasks that do change things, the pattern from the tuning post still applies: read the current state first, then use when so the change only runs if needed. The read runs in check mode; the change is skipped, but you can add a task that reports the would-be change:
- name: Report profile drift
ansible.builtin.debug:
msg: "tuned profile is not {{ lowlat_tuned_profile }}"
when: lowlat_tuned_profile not in tuned_active.stdout
changed_when: true
changed_when: true on a debug task looks odd, but it makes the drift count show up in the recap where your alert looks for it.
If a task can’t work in check mode at all, skip it explicitly with the ansible_check_mode variable rather than letting it fail:
- name: Regenerate something that has no check support
ansible.builtin.command: /usr/local/bin/rebuild-cache
when: not ansible_check_mode
Then write down somewhere that this part isn’t covered by the drift check.
5. Keep secrets out of the diff
--diff prints file contents. If a template contains a password or a key, the diff will print it, and your drift log is now a secret store. The docs mention this directly. Turn diff off on those tasks:
- name: Template app credentials
ansible.builtin.template:
src: creds.conf.j2
dest: /etc/app/creds.conf
mode: "0600"
diff: false
The task still reports changed if the file drifted. You just don’t see the lines. no_log: true hides more, including the task result, and is worth adding where the module output itself contains secrets.
6. Get to zero first
A drift check only works if a clean host reports zero changes. If ten tasks report changed on every run, nobody will read the eleventh.
Run the play normally on a host, then run it again in check mode. Every changed in the second run is either real drift (unlikely, you just applied it) or a task that isn’t idempotent. Fix those first:
- Read-only
command/shelltasks:changed_when: false,check_mode: false. - Tasks that template a timestamp or a random value: remove it.
- Tasks that always restart a service: use a handler.
Do this in dev, then stg, then prd, the same way you promote a change. When all three report zero on a clean run, the check is ready.
7. Comparing prd, stg and dev
Because the inventory is grouped by environment, you can run the same check against each group and compare:
for env in dev stg prd; do
ansible-playbook -i inventory/hosts.yml site.yml \
--limit "$env" --check --diff \
> "drift-$env.log" 2>&1
done
What the results tell you:
- Drift only in prd: someone changed prd by hand. Find out why. Either the fix goes into the repo, or the host gets put back.
- Drift in prd and stg, not dev: a change was made in dev and the repo, but not promoted yet. That’s expected during a rollout. If it’s been there for weeks, the rollout stalled.
- Drift everywhere on the same task: probably the code changed and nobody ran it, or a package update touched the same file on every host.
- One host differs from the rest of its group: often a rebuild from an old image.
Remember that check mode compares each host against the code, not hosts against each other. If a setting differs between environments on purpose (through group_vars), check mode won’t flag it, which is what you want.
8. Machine-readable output
The default output is for people. For a scheduled job you want counts per host. The ansible.posix.json callback prints the whole run as one JSON document at the end, including a stats section with ok, changed, failures, unreachable and skipped per host:
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json \
ansible-playbook -i inventory/hosts.yml site.yml \
--limit prd --check > drift-prd.json
Then count:
jq -r '.stats | to_entries[]
| select(.value.changed > 0 or .value.failures > 0 or .value.unreachable > 0)
| "\(.key) changed=\(.value.changed) failed=\(.value.failures) unreachable=\(.value.unreachable)"' \
drift-prd.json
The ansible.posix collection needs to be installed; pin it in requirements.yml with the rest. If you keep the human-readable diff as well, run a second pass with --diff and save it as the attachment for whoever picks up the alert. Leave --diff off the JSON run if any task might leak a secret you missed.
Don’t rely on the exit code alone. A run where hosts report changed still exits zero, because from Ansible’s point of view nothing went wrong. Failed or unreachable hosts give a non-zero exit code. So the job should treat non-zero as “the check itself is broken” and the changed count as “drift”.
9. Running it on a schedule
Any scheduler works: cron on a management host, a CI job, AWX. I run it as a scheduled CI pipeline, so every run has a log, a history, and a failure notification without extra plumbing. The CI runner needs network access to the hosts and its own SSH key. The shape is the same:
- Check out the main branch, the same commit that was last applied.
- Install the pinned collections.
- Run each environment in check mode with JSON output.
- Count hosts with
changed,failedorunreachable. - If anything is non-zero, alert, with the host list and the diff attached.
- Keep the logs for a while, so you can see when drift started.
A few practical points:
- Check out what was applied, not the newest commit. If someone merged a change that hasn’t rolled out, every host will show “drift” for it. Either check against the last applied commit or accept that open rollouts show up, and label them.
- Run outside change windows. A check during a rollout reports half-applied hosts.
- Use a read-only account if you can. Check mode still needs
becomefor many reads, but the account running scheduled checks doesn’t need to be the one that runs changes. Combined withcheck_mode: falseonly on read-only tasks, this limits the damage of a mistake. - Pass the safety flags the play needs. In the tuning play, the change-window assert would stop the run in prd. Check mode changes nothing, so it’s reasonable to let the assert pass when
ansible_check_modeis true, rather than passinglowlat_change_window_open=truefrom the scheduler.
- name: Refuse to run outside the change window
ansible.builtin.assert:
that: >-
ansible_check_mode
or not lowlat_require_change_window | bool
or lowlat_change_window_open | default(false) | bool
10. What to do with an alert
An alert should lead to one of two outcomes:
- The change was right. Put it in the repo, review it, promote it dev → stg → prd like any other change.
- The change was wrong or unknown. Run the play normally on that host, in a change window, to put it back.
What you don’t want is a drift alert that stays open for weeks because nobody owns it. If the same host drifts on the same task every week, something is changing it: a cron job, another tool, an agent. Find it and either manage it in the play or stop it.
How often to run is a trade-off. Daily is a reasonable start for most fleets. More often just means more noise during rollouts.
Checklist
- A clean host reports zero
changedin check mode, in every environment - Read-only
command/shelltasks havecheck_mode: falseandchanged_when: false - Known gaps (modules without check support, skipped commands) written down
-
diff: falseorno_log: trueon tasks that touch secrets - Scheduled run per environment with
ansible.posix.jsonoutput - Alert on
changed,failuresorunreachable> 0; treat non-zero exit as a broken check - Check against the last applied commit, outside change windows
- Every alert ends with the repo updated or the host put back