Bootstrap FreeKB - Ansible - check_mode parameter (dry run)
Ansible - check_mode parameter (dry run)

Updated:   |  Ansible articles

There are two ways to determine if plays in a playbook will be successful, like a dry run, meaning that no changes will be made on the target systems.

The --check flag will check every task in every play in a playbook. The check_mode parameter will only check certain tasks.

Let's say you've a playbook named example.yml that is using lineinfile to append "Hello World" to /tmp/foo.txt, like this. Notice check_mode is being used.

---
- hosts: all
  tasks:
  - name: append 'Hello World' to /tmp/foo.txt
    ansible.builtin.lineinfile:
      path: /tmp/foo.txt
      line: Hello World
    check_mode: yes
...

 

Something like this should be returned.

TASK [append 'Hello World' to /tmp/foo.txt]
changed: [server1.example.com]

PLAY RECAP
server1.example.com : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

On the target system, "Hello World" would NOT have been appended to /tmp/foo.txt since check_mode was used. Now let's invoke the ansible-playbook command check_mode.

---
- hosts: all
  tasks:
  - name: append 'Hello World' to /tmp/foo.txt
    ansible.builtin.lineinfile:
      path: /tmp/foo.txt
      line: Hello World
...

 

This should produce the same exact output, which is something important to be aware of. check_mode will not change the output produced by the ansible-playbook command. However, now "Hello World" should have been appended to /tmp/foo.txt on the target system. Just like check_mode, the --check flag will not change the output produced by the ansible-playbook command.

TASK [append 'Hello World' to /tmp/foo.txt]
changed: [server1.example.com]

PLAY RECAP
server1.example.com : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

It usually doesn't make sense to hard code in "check_mode: yes" in your playbooks, because then when you want to disable check mode, you would have to comment out or change the check_mode parameter to false. Instead, you could set the check_mode parameter to use a variable, like this.

---
- hosts: all
  tasks:
  - name: append 'Hello World' to /tmp/foo.txt
    ansible.builtin.lineinfile:
      path: /tmp/foo.txt
      line: Hello World
    check_mode: "{{ mode }}"
...

 

Then, when using the ansible-playbook command, the --extra-vars command line flag could be used to set the mode variable to either "yes" or "no".

ansible-playbook example.yml --extra-vars "mode=yes"

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1d4eb2 in the box below so that we can be sure you are a human.