joao cenoura
joao cenoura

Reputation: 1225

Ansible include_vars continue if file not found

If I have something like this:

- include_vars: this_file_doesnt_exist.yml

ansible will throw the error "input file not found at ..." and stop the provisioning process.

I'm wondering if it's possible to allow the provisioning process to continue if the file isn't found.

My use case is the following:

Example:

- include_vars: aptcacher.yml

- name: use apt-cache
  template: src=01_proxy.j2 dest=/etc/apt/apt.conf.d/01_proxy owner=root group=root mode=644
  sudo: true
  when: aptcacher_host is defined

Ansible version: 1.9.1

Upvotes: 9

Views: 11518

Answers (3)

stackprotector
stackprotector

Reputation: 13550

To optionally include variables, you can use the with_first_found loop which is based on the ansible.builtin.first_found lookup. With skip: true, you can assert that it does not error, when it does not find any files:

- include_vars: '{{ item }}'
  with_first_found:
    - files:
        - this_file_doesnt_exist.yml
      skip: true

From Ansible 2.2 on, you can also use a regex pattern for files to include. The module will not error if it does not find any files. Caveat: You have to provide a directory name, that does exist:

- include_vars:
    dir: vars
    files_matching: this_file_doesnt_exist.yml

Upvotes: 0

ProfHase85
ProfHase85

Reputation: 12193

You can just ignore_errors on the include_vars task:

- include_vars: nonexistant_file
  ignore_errors: yes

EDIT

With ansible > 1.6.5 I am getting

test.yml

---

- hosts: localhost
  tasks:
    - include_vars: nonexistent_file
      ignore_errors: yes

    - debug:
        msg="The show goes on"

PLAY [localhost]


GATHERING FACTS *************************************************************** ok: [localhost]

TASK: [include_vars nonexistent_file] ***************************************** failed: [localhost] => {"failed": true, "file": "/home/ilya/spielwiese/ansible/nonexistent_file"} msg: Source file not found. ...ignoring

TASK: [debug msg="The show goes on"] ****************************************** ok: [localhost] => { "msg": "The show goes on" }

Upvotes: 5

udondan
udondan

Reputation: 60009

You can use with_first_found to archive this.

- include_vars: "{{ item }}"
  with_first_found:
   - this_file_doesnt_exist.yml

I'm not 100% sure it will work without complain if not at least one file matched. In case it doesn't work, you will need to add an empty fallback file:

- include_vars: "{{ item }}"
  with_first_found:
   - this_file_doesnt_exist.yml
   - empty_falback.yml

Upvotes: 1

Related Questions