Copying Files with Ansible
One of the most common tasks in infrastructure automation is copying files from the control node (the machine running Ansible) to the remote hosts. Ansible provides a simple and efficient way to accomplish this task using the copy
module.
The copy
Module
The copy
module in Ansible is used to copy files from the control node to the remote hosts. It supports various options, such as:
src
: The source file or directory on the control node.
dest
: The destination path on the remote host.
owner
: The owner of the file on the remote host.
group
: The group of the file on the remote host.
mode
: The permissions of the file on the remote host.
Copying a Single File
To copy a single file from the control node to a remote host, you can use the following Ansible playbook:
- hosts: all
tasks:
- name: Copy a file
copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
owner: myuser
group: mygroup
mode: "0644"
In this example, the copy
module is used to copy the file file.txt
from the local path /path/to/local/file.txt
to the remote path /path/to/remote/file.txt
. The file will be owned by the myuser
user and the mygroup
group, and it will have permissions of 0644
(read-write for the owner, read-only for the group and others).
Copying a Directory
To copy an entire directory from the control node to a remote host, you can use the following Ansible playbook:
- hosts: all
tasks:
- name: Copy a directory
copy:
src: /path/to/local/directory/
dest: /path/to/remote/directory/
owner: myuser
group: mygroup
mode: "0755"
recursive: yes
In this example, the copy
module is used to copy the contents of the local directory /path/to/local/directory/
to the remote directory /path/to/remote/directory/
. The recursive
option is set to yes
to ensure that the entire directory structure is copied. The files and directories will be owned by the myuser
user and the mygroup
group, and they will have permissions of 0755
(read-write-execute for the owner, read-execute for the group and others).
By using the copy
module, you can easily and efficiently copy files and directories from the control node to the remote hosts, streamlining your infrastructure automation workflows.