Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use lookup('file') in ansible when the file might not exist?

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?

like image 385
Ben Avatar asked Mar 13 '15 18:03

Ben


People also ask

How does lookup work in Ansible?

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.

What is lookup in Ansible playbook?

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.

How do I read Ansible file content?

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.

What is a lookup file?

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.


1 Answers

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') }}"
like image 175
Bert Van Landeghem Avatar answered Oct 19 '22 11:10

Bert Van Landeghem