To avoid the error when the path doesn t exist, use a condition to check for the path before attempting the lookup:
---
- hosts: localhost
tasks:
- debug: msg="{{ lookup( ini , foo section=DEFAULT file=missing-file.conf ) }}"
when: missing-file.conf | exists
You can use this with set_fact
as well, then omit the undefined var when using it if required:
- hosts: localhost
tasks:
- set_fact:
foo: "{{ lookup( ini , foo section=DEFAULT file=missing-file.conf ) }}"
when: missing-file.conf | exists
- debug:
var: foo # undefined
msg: "{{ foo | default(omit) }}" # omitted
Note that lookups and Jinja2 tests run on the controller. If you need to check the path on the host, use the stat
and either slurp
or fetch
modules:
- stat:
file: missing-remote-file-with-text-i-want
register: file
- slurp:
src: missing-remote-file-with-text-i-want
register: slurp
when: file.stat.exists
- set_fact:
foo: "{{ slurp.content | b64decode }}"
when: file.stat.exists
- fetch:
src: missing-file.conf
dest: /tmp/fetched
fail_on_missing: False
- set_fact:
bar: "{{ lookup( ini , foo section=DEFAULT file=/tmp/fetched/ + inventory_hostname + /missing-file.conf ) }}"
when: ( /tmp/fetched/ + inventory_hostname + /missing-file.conf ) | exists
Second note, in Ansible v2.5
the grammar for using the path tests was changed, the format is now:
- set_fact:
foo: "{{ lookup( ini , foo section=DEFAULT file=missing-file.conf ) }}"
when: "missing-file.conf" is exists