I want to lookup the contents of a file on the ansible control node --
example:
- hosts: all
vars:
somevar: "{{ lookup('file', playbook_dir + '/some/path' + inventory_hostname) }}"
if the file does not exist I'd like the variable to be undefined or set to a default value. The lookup module throws an error however if the file doesn't exist. What's the right way to handle this error so that I can branch on the existence of somevar within my code?
In Ansible, using lookup plugins, we can fetch data from external resources. These sources can be local filesystems or some external datastores or services. The data obtained by those sources is then evaluated by plugins and returned using Ansible templating systems and made available in that format.
Lookup plugins are an Ansible-specific extension to the Jinja2 templating language. You can use lookup plugins to access data from outside sources (files, databases, key/value stores, APIs, and other services) within your playbooks. Like all templating, lookups execute and are evaluated on the Ansible control machine.
You can use lookups in Ansible in order to get the contents of a file, e.g. Caveat: This lookup will work with local files, not remote files. Note that lookup runs locally, while the cat command in @TesterJeff's example is running on the remote machine.
Traditionally a lookup file is a delimited text file that contains columns of data that you can join to core dimensions as Info Fields. You can generate a lookup file using a spreadsheet, text editor, or relational database.
It seems that since this original post and now, this functionality has been added to the lookup plugin.
For me it works, I'm on version 2.8.5:
https://docs.ansible.com/ansible/latest/plugins/lookup.html#using-lookup-plugins
New in version 2.6.
You can now control how errors behave in all lookup plugins by setting errors
to ignore
, ...
- hosts: all
vars:
somevar: "{{ lookup('file', playbook_dir + '/some/path' + inventory_hostname, errors='ignore') }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With