问题
I'm sending a config file for thousands of nodes, because of some customisation there's maybe 5 or 6 paths to that file (There's only one file for host but the path can vary) and there isn't a easy way to figure out the default location with facts.
Based on this, I'm looking for some way to set the "dest" of copy module like we can set the "src", with a with_first_found loop.
Something like that:
copy: src=/foo/{{ ansible_hostname }}/nrpe.cfg dest="{{item}}
with_items:
- "/etc/nagios/nrpe.cfg"
- "/usr/local/nagios/etc/nrpe.cfg"
- "/usr/lib64/nagios/etc/nrpe.cfg"
- "/usr/lib/nagios/etc/nrpe.cfg"
- "/opt/nagios/etc/nrpe.cfg"
PS: I'm sending nrpe.cfg so if someone knows a better way to find where's the default nrpe.cfg it will be a lot easier.
EDIT 1: I've managed to work with the help from @ydaetskcoR like this:
- name: find nrpe.cfg
stat:
path: "{{ item }}"
with_items:
- "/etc/nagios/nrpe.cfg"
- "/usr/local/nagios/etc/nrpe.cfg"
- "/usr/lib64/nagios/etc/nrpe.cfg"
- "/usr/lib/nagios/etc/nrpe.cfg"
- "/opt/nagios/etc/nrpe.cfg"
register: nrpe_stat
no_log: True
- name: Copy nrpe.cfg
copy: src=/foo/{{ ansible_hostname }}/nrpe.cfg dest="{{item.stat.path}}"
when: item.stat.exists
no_log: True
with_items:
- "{{nrpe_stat.results}}"
回答1:
One option could be to simply search for the already existing nrpe.cfg
file and then register that location as a variable to be used for the copy task.
You could do that either through a shell/command task that just uses find
or loop through a bunch of locations with stat to check if they exist.
So you might have something like this:
- name: find nrpe.cfg
shell: find / -name nrpe.cfg
register: nrpe_path
- name: overwrite nrpe.cfg
copy: src=/foo/{{ ansible_hostname }}/nrpe.cfg dest="{{item}}"
with_items:
- nrpe_path.stdout_lines
when: nrpe_path.stdout != ""
register: nrpe_copied
- name: copy nrpe.cfg to box if not already there
copy: src=/foo/{{ ansible_hostname }}/nrpe.cfg dest="{{ default_nrpe_path }}"
when: nrpe_copied is not defined
As Mxx pointed out in the comments, we have a third task to fall back to copying to some default path (potentially /etc/nagios/
or any other path really) if the nrpe.cfg
file hasn't been found by find
.
To use stat
rather than a shell/command task you could do something like this:
- name: find nrpe.cfg
stat:
path: {{ item }}
with_items:
- "/etc/nagios/nrpe.cfg"
- "/usr/local/nagios/etc/nrpe.cfg"
- "/usr/lib64/nagios/etc/nrpe.cfg"
- "/usr/lib/nagios/etc/nrpe.cfg"
- "/opt/nagios/etc/nrpe.cfg"
register: nrpe_stat
- name: overwrite nrpe.cfg
copy: src=/foo/{{ ansible_hostname }}/nrpe.cfg dest="{{item.stat.path}}"
when: item.stat.exists
with_items:
- "{{nrpe_stat.results}}"
来源:https://stackoverflow.com/questions/34344321/ansible-send-file-to-the-first-met-destination