Ansible include task only if file exists

I using something similar but for the file module and what did the trick for me is to check for the variable definition, try something like:

when: optional_file.stat.exists is defined and optional_file.stat.exists

the task will run only when the variable exists.


In Ansible 2.5 and above, it can be done using tests like this:

- include: /home/user/optional/file.yml
  when: "'/home/user/optional/file.yml' is file"

More details: https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html#testing-paths


Thanks all for your help! I'm aswering my own question after finally trying all responses and my own question's code back in today's Ansible: ansible 2.0.1.0

My original code seems to work now, except the optional file I was looking was in my local machine, so I had to run stat through local_action and set become: no for that particular tasks, so ansible wouldn't attempt to do sudo in my local machine and error with: "sudo: a password is required\n"

- local_action: stat path=/home/user/optional/file.yml
  register: optional_file
  become: no
- include: /home/user/optional/file.yml
  when: optional_file.stat.exists

The with_first_found conditional can accomplish this without a stat or local_action. This conditional will go through a list of local files and execute the task with item set to the path of the first file that exists. Including skip: true on the with_first_found options will prevent it from failing if the file does not exist.

Example:

- hosts: localhost
  connection: local
  gather_facts: false

  tasks:
    - include: "{{ item }}"
      with_first_found:
        - files:
            - /home/user/optional/file.yml
          skip: true

Tags:

Ansible