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.

 myhosts
[servers]
node1 ansible_host=10.1.1.51
node2 ansible_host=10.1.1.52
node3 ansible_host=10.1.1.53

A Playbook with the copy Task:

 playbook-copyfiles.yml
---
- name: Playbook to copy files
  become: true
  hosts: all

  tasks:

    - name: Copy file with owner and permissions
      copy:
        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