Last active
June 16, 2021 11:04
-
-
Save aderixon/713b1158e7f9cd92ab2baa61a0fb167c to your computer and use it in GitHub Desktop.
Ansible file lookups when file is potentially not present
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.