How to locate the proper file?

15 views
Skip to first unread message

Werner Flamme

unread,
Jun 7, 2016, 9:52:16 AM6/7/16
to Ansible Project
Hi everyone,

I have to copy a file (on the client) to a certain location (also on the
client).

I know the copy module, but my problem is the source location. The
filename is always the same, like foo.pem.

- if the directory "/some/dir/{{ ansible_hostname }}" does not exist, I
have to create a new file
- if this directory exists, it may have a subdirectory "in_2016". If
this is the case, I have to take the file foo.pem from here
- if not, there may be a subdirectory "in_2015". If this is the case, I
have to take the file foo.pem from here
... plus several older directories.

A construction "with_first_found:" can't be applied here, can it?

Currently I try something like

=== snip ===
- name: find proper directory (2016)
find: paths=/some/dir/{{ ansible_hostname }}/in_2016 file_type=directory
register: dir2016
ignore_errors: True

- debug: var=dir2016

- name: find proper directory (2015)
find: paths=/some/dir/{{ ansible_hostname }}/in_2015 file_type=directory
register: dir2015
ignore_errors: True
when: dir2016.rc != 0

=== snip ===

But then I have to use a bazillion of copy commands containing "when:
dir20xx == 0".

Is there a better way to get this done? I'm using ansible 2.1.0.0 on
SLES 11 SP4.

Maybe it is best to copy a (bash) script to the host and execute it, but
I prefer the documented way via ansible ;)

Regards,
Werner

--

Werner Flamme

unread,
Jun 9, 2016, 6:10:18 AM6/9/16
to Ansible Project
Werner Flamme [07.06.2016 15:52]:
> Hi everyone,
>
> I have to copy a file (on the client) to a certain location (also on the
> client).
>
> I know the copy module, but my problem is the source location. The
> filename is always the same, like foo.pem.

[...]

JFTR:

By reading "Mastering Ansible", written by by Jesse Keating, I found out
about the stat module, "set_facts" and registered variables in loops...
So I think I solved my problem now with two tasks:

=== snip ===
- vars:
mydirlist:
- in_2014
- in_2014_09
- in_2015
- in_2016
mytargetdir: 'nonsense'

- name: figuring the directory
stat: path=/some/dir/{{ ansible_hostname }}/{{ item }}
register: fig1
with_items: "{{ mydirlist }}"

- name: note the first found path
set_fact: mytargetdir="{{ item.stat.path }}"
with_items: "{{ fig1.results }}"
when: mytargetdir == 'nonsense' and item.stat.exists == True
=== pins ===

Regards,
Werner

--

Reply all
Reply to author
Forward
0 new messages