I'm very new to Ansible and I'm trying to check if files exists in my Ansible control machine(At least one should be), if so copy to remote location.
I've came up with the below, but ansible is checking the files in the remote instead of local. I'm not exactly sure -how to use "with_items" as well.
---
- hosts: linux
gather_facts: no
vars:
source_dir: /login/my_home
server_type: WRITEVIEW
files:
- app.xslt
- Configuration.xml
- fcCN.xslt
tasks:
- name: Validate if file exists
local_action: file path="{{ source_dir }}/{{ item }}" state=file
with_items: files
Error Message:
TASK [Validate if file exists] ******************************************************************************************************************************************
failed: [remoteserver_1 -> localhost] (item=files) => {"changed": false, "item": "files", "msg": "file (/login/my_home/files) is absent, cannot continue", "path": "/login/my_home/files", "state": "absent"}
failed: [remoteserver_2 -> localhost] (item=files) => {"changed": false, "item": "files", "msg": "file (/login/my_home/files) is absent, cannot continue", "path": "/login/my_home/files", "state": "absent"}
You can use the stat command to check whether a file exists or not. If exists, then copy it to the remote server :
---
- hosts: linux
gather_facts: no
vars:
source_dir: /login/my_home
server_type: WRITEVIEW
files:
- app.xslt
- Configuration.xml
- fcCN.xslt
tasks:
- name: check if file exists
local_action: stat path=/path/of/file/{{ item }}
with_items: "{{ files }}"
register: check_file_name
- name: Verifying if file exists
debug: msg="File {{ item.item }} exist"
with_items: "{{ check_file_name.results }}"
when: item.stat.exists
- name: Copying the file
copy: src=/path/of/file/local/{{ item.item }} dest=/path/of/file/remote/
with_items: "{{ check_file_name.results }}"
when: item.stat.exists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With