Ansible’s Copy and Fetch Modules

Ansible Copy and Fetch in action

If you are moving files between computers then you may be doing this by transferring the files to a physical medium (e.g. a USB pen drive), via email or via scp. However, there are other options including Ansible which has two modules to help, Copy and Fetch.

A basic Ansible Playbook to demonstrate the Copy and Fetch modules


The Copy module can be used to copy files to a remote destination i.e. copying a configuration file to several remote hosts at the same time.

- name: Copy File To Pi4


    src: test_file_to_copy.txt

    dest: /home/pi/test_file_to_copy.txt

- name: Copy File To Pi4 and Backup Original On Pi4


    src: topsecret.txt

    dest: /home/pi/topsecret.txt

    backup: yes

My example shows two of the options available with the Copy module. The first requires:

  • a source (src) which can be just the filename if the file exists in the same directory as the playbook, or can include a file path if needed
  • a destination (dest) which is where the file will be saved on the remote host

Note: You may need to use the become: option if you are saving to an area that requires higher privileges to write to.

The second example includes the backup: option. If the file being copied already exists on the remote server (i.e. where the file is being copied to) then this option renames the file on the remote server and copies the file from the ansible machine to the remote server.

topsecret.txt.15257 was the original topsecret.txt on the Pi4
topsecret.txt.15257 was the original topsecret.txt on the Pi4

Copy also has options for setting the files permissions whilst copying.


Fetch is the opposite of Copy, as it fetches files from remote servers to the computer running Ansible.

- name: Fetch A File From Pi4


    src: /home/pi/info.txt

    dest: info.txt
The source (src) is the location of the file on the remote machine, e.g. in this example it is the info.txt file under /home/pi on my Raspberry Pi.
The destination (dest) is where the file should be copied to on the machine running Ansible, if just a filename is given then the file will be saved to the directory where the Ansible playbook is running from.

More Information:

To find out more about Copy and Fetch please visit the official documentation on the Ansible website: