Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

jinja2

I was a little bit surprised to discover that his piece of code fails with an IOError exception instead of defaulting to omitting the value.

#!/usr/bin/env ansible-playbook -i localhost,
---
- hosts: localhost
  tasks:
    - debug: msg="{{ lookup('ini', 'foo section=DEFAULT file=missing-file.conf') | default(omit) }}"

How can I load a value without raising an exception?

Please note that the lookup module supports a default value parameter but this one is useless to me because it works only when it can open the file.

I need a default value that works even when the it fails to open the file.

like image 406
sorin Avatar asked Apr 04 '17 15:04

sorin


Video Answer


1 Answers

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.

like image 175
Konstantin Suvorov Avatar answered Oct 27 '22 19:10

Konstantin Suvorov