Skip to content

Instantly share code, notes, and snippets.

@aderixon
Last active June 16, 2021 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
vars:
filelist:
- thisfile
- thatfile
tasks:
# OPTION 1:
# check for each file individually
- name: check files exist
stat:
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
# OPTION 2:
# alternatively, get a list of all the files (with optional excludes)
- name: get list of all files
local_action:
module: find
paths: "path/to/files" # e.g. "{{ (playbook_dir + '/blah/dir') }}"
excludes: '*~'
register: allfiles
- name: output file contents
debug:
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
@mrjk
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.

@aderixon
Copy link
Author

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