Testing

What Check Mode Actually Proves: Validating Playbooks Before a Real Run

A clean --check run is a prediction made by the modules that support check mode, not a proof that your play is correct. This guide builds a complete localhost reproduction in a temporary directory, compares --syntax-check, --check --diff, a real run and a second real run, and shows exactly which parts of a play check mode cannot tell you anything about — including the tasks it silently skips and the diff output that leaks file contents.

Version scope and prerequisites

Written against ansible-core 2.22.0, released 2026-11-02, which requires a controller Python of 3.13 to 3.15. Check mode itself is long-standing: check_mode as a task keyword arrived in 2.2, the ansible_check_mode variable in 2.1, and diff: false in 2.4. Nothing here depends on a recent feature, so it applies to older releases too.

The reproduction writes one file into a directory you create with mktemp -d and nothing else. It is not intended for the playground on this site, which runs ansible-core 2.22.0 but always runs with --check and screens inputs — this article is about the comparison between modes, which needs a real run in your own environment.

Check mode is not a security boundary and not a compliance proof. Modules that do not implement check mode report nothing and do nothing, modules that implement it imperfectly can still have side effects, and check_mode: false makes a task run for real regardless of the flag. Support also varies by module in ways the module itself declares: raw declares no check-mode support, while command, shell and script declare partial support — they can predict a changed status, but only through their creates/removes options (module source). A green --check run is evidence about the tasks that participated in it, nothing more. Run these examples on a machine you own.

Common setup

mkdir -p ~/tma-checkmode && cd ~/tma-checkmode
python3.13 -m venv .venv
.venv/bin/python -m pip install 'ansible-core==2.22.0'
.venv/bin/ansible --version
[defaults]
interpreter_python = auto_silent
[local]
localhost ansible_connection=local

What the two modes actually are

Check mode runs the play without making changes on the target. Modules that support it report the changes they would have made. Modules that do not support it report nothing and do nothing. Upstream's own description is blunt: check mode is just a simulation, and it will not generate output for tasks that use conditionals based on registered variables. That last clause is narrower than it first reads — read-only modules do register real results under --check — and the section on skipped tasks below pins down which registered values are actually untrustworthy.

Diff mode is separate and composable. --diff alone shows what changed; with --check it shows what would change. It is most useful on file-manipulating modules such as template and copy, but others — user, for instance — also report before and after. It produces a lot of output, so upstream recommends one host at a time: --check --diff --limit one.example.com.

Four commands, four different claims

Before the reproduction, it is worth naming what each step in a validation pipeline proves, because they are routinely conflated in CI configuration.

  • --syntax-check parses the playbook, and the files it statically imports, and resolves the action and module names it finds. It proves the YAML loads, the play structure is well formed, and every module named in the parsed files can be resolved — a typo such as ansible.builtin.cpoy fails here. What it does not do is evaluate expressions, contact any host, confirm that the installed collection version supports the options you passed, or reach inside dynamic includes, which are resolved only at run time.
  • --check connects, gathers facts, and asks each participating module to predict. It proves the play runs end to end against real facts and that the predicting modules see work to do. It does not prove the work succeeds.
  • A real run proves the play applies on this host, in this state, once.
  • A second real run is the idempotence test: a recap with changed=0 is the cheapest useful evidence that the play converges rather than churning. It is still only what the modules reported — a task carrying changed_when: false will show changed=0 while rewriting a file every run — so pair the recap with a comparison of actual state, as the reproduction below does with stat. This is the step most often missing, and it catches a class of bug that no amount of check-mode running will.

The reproduction

The play below takes its working directory from a variable and refuses to start without one, records the state of the target file both before and after the write, and guards each assertion with ansible_check_mode so the right claim is tested in the right mode. The variable is a single place to point at a throwaway directory; it is not a containment mechanism — keeping the play away from real paths is a matter of passing it a mktemp -d path, as every command below does.

---
- name: Compare predicted and applied state in a temporary directory
  hosts: local
  gather_facts: false

  vars:
    config_body: |
      [service]
      workers = 4

  tasks:
    - name: Fail early if the caller did not pass a working directory
      ansible.builtin.assert:
        that:
          - work_dir is defined
          - work_dir | length > 0
        fail_msg: Use a fresh temporary directory created with mktemp -d.

    - name: Record the state of the path before the play touches it
      ansible.builtin.stat:
        path: "{{ work_dir }}/service.conf"
      register: before

    - name: Write the configuration file
      ansible.builtin.copy:
        content: "{{ config_body }}"
        dest: "{{ work_dir }}/service.conf"
        mode: "0640"
      register: config_file

    - name: Record the state of the path afterwards
      ansible.builtin.stat:
        path: "{{ work_dir }}/service.conf"
      register: after

    - name: Report the mode, the prediction, and the real state together
      ansible.builtin.debug:
        msg:
          check_mode: "{{ ansible_check_mode }}"
          reported_changed: "{{ config_file.changed }}"
          existed_before: "{{ before.stat.exists }}"
          exists_after: "{{ after.stat.exists }}"

    - name: Under --check the existence of the path did not change
      ansible.builtin.assert:
        that:
          - after.stat.exists == before.stat.exists
        success_msg: Check mode did not create or remove the path (existence only).
      when: ansible_check_mode

    - name: Only a real run is allowed to assert the applied state
      ansible.builtin.assert:
        that:
          - after.stat.exists
          - after.stat.mode == "0640"
        success_msg: The file exists with the expected mode (contents not asserted here).
      when: not ansible_check_mode

    - name: A command task with no creates/removes is skipped under --check
      ansible.builtin.command:
        cmd: "wc -l {{ work_dir }}/service.conf"
      changed_when: false
      register: line_count

    - name: Distinguish a skipped prediction from a real result
      ansible.builtin.debug:
        msg: >-
          {{
            'command skipped under --check, any stdout here is a placeholder'
            if line_count.skipped | default(false)
            else 'command ran, stdout: ' ~ line_count.stdout
          }}

    - name: A read-only probe may opt out of check mode deliberately
      ansible.builtin.command:
        cmd: /bin/true
      check_mode: false
      changed_when: false
      register: probe

    - name: The opted-out probe really runs in both modes
      ansible.builtin.assert:
        that:
          - probe.rc == 0
          - not probe.skipped | default(false)

Step 1 — syntax check

.venv/bin/ansible-playbook -i hosts.ini check-demo.yml --syntax-check

Expected result: two lines, playbook: check-demo.yml, and exit status 0. Every module name in the file was resolved to pass this step. What the syntax check did not do is evaluate anything: work_dir is undefined at this point and it does not care, because it never evaluates the assertion. That is the limit of this step in one sentence.

Step 2 — check mode with a diff, on a fresh directory

WORK_DIR=$(mktemp -d)
echo "$WORK_DIR"
.venv/bin/ansible-playbook -i hosts.ini check-demo.yml -e work_dir="$WORK_DIR" --check --diff
ls -la "$WORK_DIR"

Expected result — a predicted change, a diff, and an empty directory afterwards:

TASK [Write the configuration file] *****
--- before
+++ after: /tmp/tmp.XXXXXXXXXX/service.conf
@@ -0,0 +1,2 @@
+[service]
+workers = 4

changed: [localhost]

TASK [Report the mode, the prediction, and the real state together] *****
ok: [localhost] => {
    "msg": {
        "check_mode": true,
        "existed_before": false,
        "exists_after": false,
        "reported_changed": true
    }
}

TASK [Under --check the existence of the path did not change] *****
ok: [localhost] => {
    "changed": false,
    "msg": "Check mode did not create or remove the path (existence only)."
}

TASK [Only a real run is allowed to assert the applied state] *****
skipping: [localhost]

TASK [A command task with no creates/removes is skipped under --check] *****
skipping: [localhost]

TASK [Distinguish a skipped prediction from a real result] *****
ok: [localhost] => {
    "msg": "command skipped under --check, any stdout here is a placeholder"
}

localhost : ok=9  changed=1  unreachable=0  failed=0  skipped=2

The ls afterwards lists nothing but . and ... That is the whole point of the before/after stat pair: the recap says changed=1 and the filesystem says otherwise, and both are correct — one is a prediction, the other is a measurement. A play that asserted after.stat.exists unconditionally would pass only by accident, when run against a host where the file already existed.

Note what that assertion does and does not establish. Comparing before.stat.exists with after.stat.exists shows that check mode did not create or delete the path; it says nothing about contents, mode or ownership, which can differ while exists stays true on both sides. If you want a stronger claim on a path that already exists, compare stat's checksum and mode fields across the pair rather than just exists.

Step 3 — the real run

.venv/bin/ansible-playbook -i hosts.ini check-demo.yml -e work_dir="$WORK_DIR"

Expected result:

TASK [Report the mode, the prediction, and the real state together] *****
ok: [localhost] => {
    "msg": {
        "check_mode": false,
        "existed_before": false,
        "exists_after": true,
        "reported_changed": true
    }
}

TASK [Only a real run is allowed to assert the applied state] *****
ok: [localhost] => {
    "changed": false,
    "msg": "The file exists with the expected mode (contents not asserted here)."
}

TASK [Distinguish a skipped prediction from a real result] *****
ok: [localhost] => {
    "msg": "command ran, stdout: 2 /tmp/tmp.XXXXXXXXXX/service.conf"
}

localhost : ok=10  changed=1  unreachable=0  failed=0  skipped=1

Ten tasks reported ok this time rather than nine, because the command task ran instead of being skipped. The wc output appears, and the mode assertion can finally be made. The assertion covers existence and mode; if the contents matter to you, add a checksum comparison or read the file back — the recap's changed=1 only says copy reported a write.

Step 4 — the second run, and check mode after the fact

.venv/bin/ansible-playbook -i hosts.ini check-demo.yml -e work_dir="$WORK_DIR"
.venv/bin/ansible-playbook -i hosts.ini check-demo.yml -e work_dir="$WORK_DIR" --check
rm -rf "$WORK_DIR"

Expected results, in order:

localhost : ok=10  changed=0  unreachable=0  failed=0  skipped=1

localhost : ok=9   changed=0  unreachable=0  failed=0  skipped=2

changed=0 on the second real run is the idempotence evidence — reported idempotence, to be exact. It is the modules' own accounting, and it can be silenced: a task with changed_when: false, or a module that cannot detect its own drift, keeps the counter at zero while the host moves underneath you. Treat it as a strong, cheap signal, and confirm it against measured state the way the stat pair above does. The final --check run is the other useful direction: run against a host that is already converged, check mode predicts no change, and that is a cheap drift signal you can schedule. Read it carefully, though — it only covers the modules that participate, so it detects drift in the file but is blind to anything a skipped command task would have inspected.

The negative case: forgetting the variable

.venv/bin/ansible-playbook -i hosts.ini check-demo.yml --check

Expected result — the guard fires before anything else happens, and the play fails:

fatal: [localhost]: FAILED! => {
    "assertion": "work_dir is defined",
    "changed": false,
    "evaluated_to": false,
    "msg": "Use a fresh temporary directory created with mktemp -d."
}

localhost : ok=0  changed=0  unreachable=0  failed=1

A guard like this belongs on any play that writes to a path supplied from outside, but be precise about what it buys you. Ansible rejects an undefined variable on its own — an undefined work_dir does not silently become an empty string or a path under the current directory — so the guard is not what prevents the write. What it adds is a failure at the top of the play, with a message naming the fix, instead of a templating error from whichever task happened to reference the variable first.

What the guard cannot do is make the path safe. work_dir is defined and work_dir | length > 0 accept any non-empty string, including /etc or /; an assertion on a variable is not containment. Containment comes from the value you pass, which is why every command in this article passes a fresh mktemp -d directory and deletes it afterwards.

Skipped is not the same as succeeded

The single most misread line in a check-mode run is skipping: [localhost] on a command, shell or script task. Those three declare partial check-mode support: hand them creates or removes and they inspect that path under --check and report a real changed status; give them neither — as the reproduction does — and they decline to guess and skip instead. raw declares no check-mode support at all, and the documented consequence of that declaration is that the action is skipped (command module source: “check_mode partial support, since it only really works in checking creates/removes”).

The trap is what the registered result then contains. The skipped task reports skipped: true, but on ansible-core 2.22 command also promises cmd, rc, stdout and stderr on every return, so the result you registered holds rc: 0 with an empty stdout and stderr rather than nothing at all. Do not rely on either shape: a condition on result.rc can evaluate cleanly against that placeholder and take the wrong branch, while another module or collection may omit the keys and raise an undefined-attribute error instead. What is reliably true is that no useful command output is available — inspect the skipped flag, not the data keys.

The debug task in the reproduction shows the defensive shape: branch on line_count.skipped | default(false) before touching line_count.stdout. The same pattern works for changed_when and failed_when expressions that depend on a registered result.

This is the sharp edge of upstream's warning that check mode does not generate output for conditionals based on registered variables — though the warning is narrower than a blanket ban on registered variables. Read-only modules run normally under --check: the reproduction's stat tasks register genuine filesystem data, and setup gathers genuine facts. The values to distrust are the ones registered by tasks that were skipped, and the ones registered by tasks whose result was a prediction rather than a measurement — those may be missing the fields your condition reads, or describe work that never happened.

Forcing and preventing check mode per task

Two task keywords exist, and they are frequently described backwards. The difference is worth getting exactly right, because one of them makes a task run for real during what you believed was a dry run.

  • check_mode: true — always simulate this task, even when the playbook is run without --check. Useful for registering what a module would do without doing it — but only for a module that implements check mode. Put it on a command or shell task with no creates/removes and the task is skipped in every mode, which registers a placeholder rather than a probe result.
  • check_mode: false — always run for real, even when the playbook is run with --check. This is an escape hatch, not a way to skip a task.

To genuinely skip a task during a dry run, use the ansible_check_mode variable in a condition. That is the mechanism upstream documents for the purpose, and it is what the reproduction uses on both assertion tasks:

The two tasks below are illustrative and were not executed. Unlike the localhost reproduction above, they name a remote repository and a health-check binary that do not exist on your machine, and they write to /srv. They are here to show the shape of the keyword, not to be pasted into a run.
# ILLUSTRATION ONLY - not executed. Needs a reachable repository,
# a writable /srv/app, and a health-check binary on the target.
- name: Skipped during a dry run, because its result would be meaningless
  ansible.builtin.git:
    repo: https://example.com/app.git
    dest: /srv/app
  when: not ansible_check_mode

- name: Errors tolerated during a dry run only
  ansible.builtin.command:
    cmd: /usr/local/bin/app-healthcheck
  changed_when: false
  ignore_errors: "{{ ansible_check_mode }}"

check_mode: false is defensible when the task is genuinely read-only and something later in the play depends on its result. Keep the command harmless and obviously side-effect-free, and say why in the task name:

- name: Read-only probe, safe to run for real during a dry run
  ansible.builtin.command:
    cmd: /bin/true
  check_mode: false
  changed_when: false
  register: probe

Never put check_mode: false on a task that installs, restarts, deletes or deploys. Someone will run the playbook with --check believing it is a dry run, and that task will do its work anyway. If you need a task excluded from dry runs, that is when: not ansible_check_mode.

Diff mode leaks file contents

This example deliberately prints a fake token to show the leak. The value is obviously fake. Do not reproduce this shape with a real credential, and do not leave --diff enabled by default in a pipeline that renders secrets.

A diff shows the lines that would change — which, for a rendered credentials file, is the credentials. The output then lands in a terminal scrollback, a CI job log, or a chat notification. The per-task opt-out is diff: false.

---
- name: A diff prints file contents unless the task opts out
  hosts: local
  gather_facts: false

  tasks:
    - name: Rendered with a diff, so the content appears in the output
      ansible.builtin.copy:
        content: "token=tma-demo-not-a-real-secret\n"
        dest: "{{ work_dir }}/leaky.conf"
        mode: "0600"

    - name: Same write with the diff suppressed
      ansible.builtin.copy:
        content: "token=tma-demo-not-a-real-secret\n"
        dest: "{{ work_dir }}/quiet.conf"
        mode: "0600"
      diff: false
WORK_DIR=$(mktemp -d)
.venv/bin/ansible-playbook -i hosts.ini diff-leak.yml -e work_dir="$WORK_DIR" --check --diff
rm -rf "$WORK_DIR"

Expected result — the first task prints the content, the second does not:

TASK [Rendered with a diff, so the content appears in the output] *****
--- before
+++ after: /tmp/tmp.XXXXXXXXXX/leaky.conf
@@ -0,0 +1 @@
+token=tma-demo-not-a-real-secret

changed: [localhost]

TASK [Same write with the diff suppressed] *****
changed: [localhost]

On ansible-core 2.22, values registered as secrets are masked in output, including in diffs, so a vault-decrypted value or one passed through register_secret would appear as $REDACTED$ here. A literal written directly into the play, as above, was never registered and is not masked — which is the point. Secret masking in 2.22 covers what is and is not registered; diff: false and no_log: true are still the controls you own.

Where check mode cannot help you

  • Modules without check-mode support. They report nothing and do nothing. Your play looks clean because half of it did not participate.
  • Command-style modules. command, shell and script support check mode only partially: with creates or removes they report a changed status from the existence of that path, and with neither they are skipped, so anything the command itself would have detected is invisible. raw has no check-mode support at all. Nothing in any of them predicts what the command would do.
  • Ordering and state dependencies. Task 3 may only make sense after task 2 actually applied. Under --check, task 2 did not apply.
  • Handlers. They are notified by changed tasks, so a dry run tells you a handler would fire, not that the service restarts cleanly.
  • Imperfect check-mode implementations. A module can support check mode and still have a side effect in some code path. Upstream's warning that check mode is "just a simulation" is about the whole mechanism, not one module.
  • check_mode: false tasks. By construction, these run for real. Audit for them before trusting any dry run on a system you care about.

For the things check mode cannot cover, you need a real run somewhere disposable. That is what Molecule and ephemeral test hosts are for, and it is why the second-run idempotence check above matters: it is the cheapest real-run test that exists.

Troubleshooting

  • "'dict object' has no attribute 'stdout'" during a dry run. You are reading a registered result from a task that was skipped. Branch on result.skipped | default(false) first. The quieter version of this bug is the one that does not error, because the module returned an empty stdout and rc: 0 alongside skipped: true; the same branch fixes both.
  • A dry run changed something. Look for check_mode: false, for modules whose check-mode implementation is incomplete, and for third-party modules and action plugins that accept the flag and ignore it. A skipped command or raw task is not the culprit — skipping is the one thing that cannot change the host.
  • --check reports changes on every run of a converged host. Usually a module comparing a value it cannot represent — a template whose output is not byte-stable, or a mode or ownership that is being reset. Run with --diff on one host to see which line moves.
  • Assertions pass in check mode and fail for real. They were asserting a prediction. Split them with when: ansible_check_mode and when: not ansible_check_mode, as in the reproduction.
  • A second real run reports changes. That is a genuine idempotence bug and no mode flag will hide it. Read the --diff output for the task that keeps changing.
  • Secrets in a CI log. Add diff: false to the task, and no_log: true if the whole result is sensitive.

Related reading

Sources