Jenkins + Ansible
Catching config drift with Ansible check mode
Run your playbooks with --check --diff on a schedule and treat every 'changed' as a question someone has to answer.
4 min readPart 4 of 4
Ansible playbooks describe how your servers should look. Servers rarely agree for long. Someone fixes an incident by editing a config file by hand and never puts the change back into the playbook. A package updates itself. A playbook change gets merged and never applied to one environment. Six months later the playbook and the servers describe two different systems, and the next real deploy "breaks" something that only worked by accident.
Check mode is a cheap way to notice before that happens.
Check mode and diff mode
ansible-playbook -i inventories/production site.yml --check --diff--check runs the playbook without changing anything, and each task reports what it would have done. --diff shows the actual difference: the lines a template would change, the permissions a file task would fix.
If your playbooks are idempotent (and they should be), then on a server that matches the playbook every task reports ok. Anything that reports changed is drift. That's the whole idea. The rest of this post is about making it trustworthy enough to run unattended.
Make the playbooks check-mode friendly
Check mode is only as good as the modules underneath it, and a few things get in the way.
command and shell tasks are skipped in check mode, because Ansible has no idea what they'd do. A playbook made mostly of shell commands will report almost nothing. Use real modules where you can (template, lineinfile, package, service). For read-only commands whose output later tasks depend on, force them to run and tell Ansible they never change anything:
- name: Read the installed agent version
ansible.builtin.command: /opt/agent/bin/agent --version
register: agent_version
check_mode: false
changed_when: falseTasks that depend on an earlier change can fail. If the playbook installs a package and then starts its service, check mode never really installs the package, so starting the service fails. Let those tasks fail quietly, but only in check mode:
- name: Start the agent
ansible.builtin.service:
name: agent
state: started
ignore_errors: "{{ ansible_check_mode }}"Some tasks report changed every single time. A command without changed_when, a template that embeds the current date, a download with force: true. They make the drift report permanently noisy, and a report that's always red gets ignored within a week. Fix these before you schedule anything.
And --diff prints file contents, which for a template full of passwords means passwords in your CI logs. Switch diff off for those tasks:
- name: Write database credentials
ansible.builtin.template:
src: db.conf.j2
dest: /etc/app/db.conf
mode: "0600"
diff: falseA result you can query
Reading the normal output by eye stops working past a few hosts. The JSON callback gives you something you can query instead:
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json \
ansible-playbook -i inventories/production site.yml --check --diff > drift.jsonWhich hosts drifted, and by how much:
jq -r '.stats | to_entries[] | select(.value.changed > 0) | "\(.key): \(.value.changed) changed"' drift.jsonWhich tasks, on which hosts:
jq -r '.plays[].tasks[] | .task.name as $task | .hosts | to_entries[]
| select(.value.changed) | "\(.key)\t\($task)"' drift.jsonThe JSON callback lives in the ansible.posix collection. If ansible-galaxy collection list doesn't show it, install it first.
Run it on a schedule
A Jenkins job that runs every weekday morning:
pipeline {
agent { label 'ansible' }
triggers { cron('H 6 * * 1-5') }
options {
timeout(time: 30, unit: 'MINUTES')
timestamps()
}
stages {
stage('Check for drift') {
steps {
sh '''
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json \
ansible-playbook -i inventories/production site.yml --check --diff > drift.json || true
jq -r '.plays[].tasks[] | .task.name as $task | .hosts | to_entries[]
| select(.value.changed) | "\\(.key)\\t\\($task)"' drift.json > drift.txt
'''
script {
if (readFile('drift.txt').trim()) {
unstable('Production has drifted from the playbooks')
}
}
archiveArtifacts artifacts: 'drift.json, drift.txt'
}
}
}
post {
unstable {
mail to: 'ops@example.com',
subject: 'Config drift in production',
body: "Details: ${env.BUILD_URL}artifact/drift.txt"
}
}
}Some of that is deliberate. The H in the cron spec lets Jenkins choose the minute, so a dozen scheduled jobs don't all start at exactly 06:00. Drift marks the build unstable rather than failed, because it's a question for a person, not a broken build. The || true after the playbook is there because check mode nearly always has a task or two that can't run; unreachable hosts still show up in the JSON stats, and they deserve their own alert. The doubled backslashes are Groovy's doing: inside a ''' string, \\( reaches the shell as \(, which is what jq expects.
What to do with the report
Every changed task is a question, and there are only two good answers.
If the manual change was right, put it in the playbook. Now the code matches reality and tomorrow's run is clean.
If it was wrong, or nobody remembers why it's there, run the playbook for real on that host and let it put things back.
The answer that isn't allowed is "leave it". A drift report people have learned to skip is worse than none at all, because it trains everyone to scroll past the one warning that's going to matter.
References
- Validating tasks: check mode and diff mode, Ansible documentation:
check_mode, theansible_check_modevariable, and turning diff off per task. - ansible.builtin.command: its partial check-mode support.
- ansible.posix.json callback.
- jq manual.
- Pipeline Syntax: cron syntax, Jenkins User Handbook: the
Hsymbol. - Pipeline: Basic Steps, Jenkins step reference:
readFileandunstable.
#ansible #ops