Dusty
Dusty

Reputation: 129

Ansible: Check if files exist and copy them

I have an ansible playbook which has a task included in it as below :

- hosts: hosts
  serial: 1
  tasks:
   - include: tasks/webapps.yaml warfiles={{ item }}
     with_items:
      - test1.war
      - test2.war

and the tasks file is :

---
   - name: Check war files in release
     local_action: stat path="/home/ansible/rel/{{ RELEASE }}/webapps/{{ warfiles}}"
     register: result
   - name: Copy war files from release
     synchronize:
       src: /home/ansible/rel/{{ RELEASE }}/webapps/{{ warfiles }}
       dest: /destination/
       checksum: yes
       archive: no
     when: result.stat.exists

When I run the playbook I get this output : TASK [Check war files in release] ********************************************** ok: [1.1.1.1 -> localhost]

TASK [Copy war files from release] *********************************************
changed: [1.1.1.1]
<fcsT...... test1.war

TASK [Check war files in release] **********************************************
ok: [1.1.1.1.1 -> localhost]

TASK [Copy war files from release] *********************************************
changed: [1.1.1.1]
<fcsT...... test2.war

Desired output: TASK [Check war files in release] ********************************************** ok: [1.1.1.1.1 -> localhost]

TASK [Copy war files from release] *********************************************
changed: [1.1.1.1]
<fcsT...... test1.war
<fcsT...... test2.war

I am trying to make the playbook to first check if the files exists and after to do the copy task so it will all show nicely. Is there a way to do it without having to have another task that I have to include. I would like to be able to "register: result" as an array and store if the files exist and after to extract the files from the array. I am new to ansible. Thank you

Upvotes: 1

Views: 12757

Answers (2)

LHSnow
LHSnow

Reputation: 1266

This can be done in one task, using with_filegblob instead. The fileglob lookup is done locally (same as local_action). This way, only war-files that exist will be copied over.

- name: Copy war files from release
  synchronize:
    src: "{{item}}"
    dest: /destination/
    checksum: yes
    archive: no
  with_fileglob: /home/ansible/rel/{{ RELEASE }}/webapps/*.war

Upvotes: 2

Raul Hugo
Raul Hugo

Reputation: 1136

Man the right use of the Stat module is on this way: You are missing the True validation.

---
   - name: Check war files in release
     local_action: stat path="/home/ansible/rel/{{ RELEASE }}/webapps/{{ warfiles}}"
     register: result
   - name: Copy war files from release
     synchronize:
       src: /home/ansible/rel/{{ RELEASE }}/webapps/{{ warfiles }}
       dest: /destination/
       checksum: yes
       archive: no
     when: result.stat.exists == True

Upvotes: 0

Related Questions