Basics of Using the Copy Module
Copying a Single File
To copy a single file from the Ansible control node to a managed node, you can use the following task:
- name: Copy a file
ansible.builtin.copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
In this example, the src
parameter specifies the local file path on the Ansible control node, and the dest
parameter specifies the remote file path on the managed node.
Copying a Directory
To copy an entire directory and its contents, you can use the following task:
- name: Copy a directory
ansible.builtin.copy:
src: /path/to/local/directory/
dest: /path/to/remote/directory/
Note the trailing slash (/
) in the src
parameter, which ensures that the contents of the directory are copied, rather than the directory itself.
Copying with Permissions and Ownership
You can set the file permissions, ownership, and group for the copied files using the following parameters:
- name: Copy a file with permissions
ansible.builtin.copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
owner: myuser
group: mygroup
mode: '0644'
In this example, the owner
and group
parameters set the file ownership, while the mode
parameter sets the file permissions in octal notation.
Conditional Copying
The copy
module supports conditional copying, where files are only copied if they have changed since the last run or if the destination file does not exist. You can use the remote_src
parameter to enable this behavior:
- name: Copy a file conditionally
ansible.builtin.copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
remote_src: yes
By setting remote_src: yes
, the copy
module will only copy the file if the destination file does not exist or if the source file has changed.
These are the basic usage patterns for the ansible.builtin.copy
module. In the following sections, we will explore more advanced configuration options and use cases.