Skip to content

Instantly share code, notes, and snippets.

Last active June 16, 2021 11:04
Show Gist options
  • Save aderixon/713b1158e7f9cd92ab2baa61a0fb167c to your computer and use it in GitHub Desktop.
Save aderixon/713b1158e7f9cd92ab2baa61a0fb167c to your computer and use it in GitHub Desktop.
Ansible file lookups when file is potentially not present
# example playbook for file lookup when file may be missing
# file lookup plugin throws an exception for a missing file that can't be caught
# so check file(s) exist first and only perform lookups on those that do
- hosts: all
become: false
- thisfile
- thatfile
# check for each file individually
- name: check files exist
path: "{{ item }}"
get_checksum: no # & disable MD5 etc to save time
with_items: "{{ filelist }}"
register: validfiles
# registered variables from loops have a complex structure, check the result here:
- debug:
var: validfiles
verbosity: 1
# alternatively, get a list of all the files (with optional excludes)
- name: get list of all files
module: find
paths: "path/to/files" # e.g. "{{ (playbook_dir + '/blah/dir') }}"
excludes: '*~'
register: allfiles
- name: output file contents
msg: "File contents are: {{ lookup('file', item.item) }}"
with_items: "{{ validfiles.results }}" # for OPTION 2, use "{{ allfiles }}" from above instead and remove conditional check
#with_items: "{{ files_wanted | intersect(allfiles) }}" # OR filter against a predefined list of relevant files
when: item.stat.exists # OPTION 1 only
Copy link

mrjk commented Jun 11, 2021

Ok, this is why Ansible sucks at some points, and this is a perfect examples, 3 tasks to do only a basic thing. Not you're fault, but Ansible can drive crazy for such little things.

Copy link

It's actually two tasks, only one of the first two is required; I've edited to try to make this clearer. As it turns out, Ansible 2.6 adds an "error='ignore'" option to the lookup plugins so all this may be redundant. However, filtering the list of files against a predefined list of interest with intersect() can be useful, e.g. for reading SSH public key files for a set of users that have them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment