loop on register

Dear ansible community,

System: CentOS 7, ansible version 2.9.17

I like to check if two files are already deployed on a node and if not it should copy the files.

For this I have the folling tasks/main.yml

# tasks file for cve
- name: Register loop output as a variable
stat:
path: “{{ item }}”
loop:
- “/tmp/test.1”
- “/tmp/test.2”
register: files

- name: Copy if file does not exist
copy:
src: test.2
dest: “/tmp/test.2”
when: item.stat.exists == false
loop: “{{ files.results }}”

And I have following files in files/:

test.1 test.2

I like to replace the following…

src: test.2
dest: “/tmp/test.2”

…through

src: “{{item.src}}”
dest: “{{item.dest}}”

…but I don’t know how to edit…

loop: “{{ files.results }}”

Is there a way to solve that? If yes, please provide the solution.

Kind regards

Michael Roessler

Maybe i'm missing something but the whole point of the copy module is
to make sure files are available on the target.
No need to stat/register/etc. This should be enough:

  - name: Ensure file is copied
    copy:
      src: "{{ item }}"
      dest: "/tmp/{{ item }}"
    loop:
      - test.1
      - test.2

I'd like to have task names that are condense and to the point, so I'm
a big fan of the simple present "ensure".

Actually it should read "Ensure file is available" - as the copying
only happens when the file is NOT available :stuck_out_tongue:

The copy happens also if source file changes.

Regards
        Racke

Dear ansible community,

System: CentOS 7, ansible version 2.9.17

I like to check if two files are already deployed on a node and if not it should copy the files.

For this I have the folling tasks/main.yml

/# tasks file for cve/
/- name: Register loop output as a variable/
/ stat:/
/ path: "{{ item }}"/
/ loop:/
/ - "/tmp/test.1"/
/ - "/tmp/test.2"/
/ register: files/
/
/
/- name: Copy if file does not exist/
/ copy:/
/ src: test.2/
/ dest: "/tmp/test.2"/
/ when: item.stat.exists == false/
/ loop: "{{ files.results }}"/

And I have following files in files/:

/test.1 test.2/

I like to replace the following...

/ src: test.2/
/ dest: "/tmp/test.2"/
...through

/ src: "{{item.src}}"/
/ dest: "{{item.dest}}"/
...but I don't know how to edit...

/ loop: "{{ files.results }}"/

Is there a way to solve that? If yes, please provide the solution.

Hello Michael,

please try:

  - name: Copy if file does not exist
    copy:
      src: "{{ item.item | basename }}"
      dest: "{{ item.item }}"
    when: item.stat.exists == false
    loop: "{{ files.results }}"

Hints:

- use debug: task to understand of the structure of {{ files.results }}
- basename: takes a path to a file and the last segment of that path (/tmp/test.1 => test.1)

Regards
        Racke