Ansible Copy File From Remote To Local Examples-DecodingDevOps

Ansible Copy File From Remote To Local Example-DecodingDevOps

Ansible Fetch Module:

To copy a file from remote to local in ansible we use ansible fetch module. Fetch module is used to fetch the files from remote to local machine. In the following example i will show you how to copy a file from remote to local using ansible fetch module.

Example 1

---
- hosts: all
  gather_facts: no
 
  tasks:
  - name: ansible copy file from remote to local.
    fetch:
     src: /root/devops/target.txt
     dest: /root/jboss/

Note: If you execute above playbook the target.txt will be copied from remote to local but entire path will be created in jboss directory. i,e target file will be located in /root/jboss/<ip of target machine>/root/devops/target.txt.

Here in the destination path you will get ip address or host-name depending upon whatever you mentioned in the inventory file. In my ansible inventory file i mentioned only ip of my target machine so i got only ip. If you mention both ip and host name in inventory file, you will get path like /root/jboss/<hostname of target machine>/root/devops/target.txt.

Result after executing ansible playbook

[root@ip-172-31-23-64 devops]# ls

target.txt

[root@ip-172-31-23-64 devops]# pwd

/root/jboss/172.31.45.181/root/devops

Ansible Copy File From Remote To Local Example 2

---
- hosts: all
  gather_facts: no

  tasks:
  - name: ansible copy file from remote to local.
    fetch:
     src: /root/devops/target.txt
     dest: /root/jboss/
     flat: yes

If you execute above playbook, you will get the file in as you expected path i,e in /root/jboss. If you mention flat as yes, you will get file into expected path and you wont get target host ip or hostname appending in the path as shown in the first example. But if you are fetching the file from multiple target machines, file will be overwritten for each host.

Result after executing ansible playbook

[root@ip-172-31-23-64 jboss]# pwd

/root/jboss

[root@ip-172-31-23-64 jboss]# ls

target.txt

Note: you can not fetch directories using fetch module. If you try to copy the directories using fetch module you will get error like “remote file is a directory, fetch cannot work on directories”

1 Response

  1. Abuthahir says:

    Where we need to mention remote server information to copy file from there?

Leave a Reply

Your email address will not be published. Required fields are marked *