How to fallback to a default value when ansible lookup fails?

As far as I know Jinja2 unfortunately doesn't support any try/catch mechanism.

So you either patch ini lookup plugin / file issue to Ansible team, or use this ugly workaround:

---
- hosts: localhost
  gather_facts: no
  tasks:
    - debug: msg="{{ lookup('first_found', dict(files=['test-ini.conf'], skip=true)) | ternary(lookup('ini', 'foo section=DEFAULT file=test-ini.conf'), omit) }}"

In this example first_found lookup return file name if file exists or empty list otherwise. If file exists, ternary filter calls ini lookup, otherwise omit placeholder is returned.


In case people like me stumble upon this question in 2022, Ansible now supports rescue blocks, which is similar to try-catch-finally in programming languages.

Examples can be found in the official documentation Error handling with blocks.


You can use block/rescue as follows:

- hosts: localhost
  tasks:
    - block:
        - debug: msg="{{ lookup('ini', 'foo section=DEFAULT file=missing-file.conf') }}"
      rescue:
        - debug: msg="omit"

Tags:

Jinja2

Ansible