Ansible - check mode with file module and dependent steps

Viewed 1625

In my ansible playbooks, I often have steps like "create a directory and then do something in it", e.g.:

- name: Create directory
  file:
    path: "{{ tomcat_directory }}"
    state: directory

- name: Extract tomcat
  unarchive:
    src: 'tomcat.tar.gz'
    dest: '{{ tomcat_directory }}'

When I run this playbook, it works perfectly fine. However, when I run this playbook in check mode, the first step succeeds (folder would have been created), but the second one fails, because the folder does not exist.

Is there any way how I could write steps like these where I create folder and then operate in it while also being able to run the playbook in check mode (without skipping such steps)?

3 Answers

Check mode can be a bit of a pain. You only really have two options:

1) Add conditionals to tasks to skip them in check mode, which you don't want to do. For reference tho:

when: not ansible_check_mode

2) You can change the behaviour of the task in check mode. If you set check_mode: no on a task, then in check mode it will behave as it would in a normal run. That is to say, despite you specifying check mode, it will actually perform the task and create the dir if it does not already exist. You have to make a choice if you are happy for a given task to run for real in check mode, so it tends to only be appropriate for low risk tasks, but does provide you a route to continue testing the rest of your playbook that is dependent on the step in question.

Ansible Check Mode Docs

You could make use of the ignore_errors task option, along with the ansible_check_mode variable, to ignore errors with your Extract tomcat task only when running in check mode, e.g.:

- name: Create directory
  file:
    path: "{{ tomcat_directory }}"
    state: directory

- name: Extract tomcat
  unarchive:
    src: 'tomcat.tar.gz'
    dest: '{{ tomcat_directory }}'
  ignore_errors: "{{ ansible_check_mode }}"

Running this in check mode will show the Extract tomcat task failed due to dest not existing. However, instead of failing the playbook, the task failure will be marked as ignored and playbook execution will continue.

An option would be to "register: result" and test "when: result.state is defined"

- name: Create directory
  file:
    path: "{{ tomcat_directory }}"
    state: directory
  register: result

- name: Extract tomcat
  unarchive:
    src: 'tomcat.tar.gz'
    dest: '{{ tomcat_directory }}'
  when: result.state is defined
Related