Using Ansible to Copy Files

Using Ansible to Copy Files

Ansible Copy Module

The copy module allows you to copy a file from the local or remote machine to a location on the remote machine. Here is an example of a inventory file and playbook.

Inventory File and Playbook

A simple inventory file.

node1 ansible_host=
node2 ansible_host=
node3 ansible_host=

A Playbook with the copy Task:

- name: Playbook to copy files
  become: true
  hosts: all


    - name: Copy file with owner and permissions
        src: /etc/hosts
        dest: /etc/hosts
        owner: root
        group: root
        mode: '0644'

In the playbook above we can see that it's grabbing the /etc/hosts file from the control workstation and copying it to the hosts files on the remote systems. Also note that you can specify a owner, group and permissions.

Running the playbook

To run the playbook, I ran the command

ansible-playbook -i myhosts -K playbook-copyfiles.yml

It resulted in the following output.

TASK [Copy file with owner and permissions] *********************************************************************************
changed: [node1]
changed: [node2]
changed: [node3]

Taking it a step further

Try implementing Ansible Templates with when doing file copies! This allows you to dynamically change the files that get copied over.

Another great tip is to run the playbook with the --diff option, it will tell you the exact changes that are being made to the files! For more information on diff check out my lesson on it