Copying Files with Ansible
Ansible provides the copy
module to copy files from the control node (where Ansible is running) to the managed nodes (the target hosts). The copy
module supports various options to control the behavior of the file copy operation.
Basic File Copy
The basic syntax for the copy
module is:
- copy:
src: <source_file>
dest: <destination_path>
Here, src
specifies the path to the file on the control node, and dest
specifies the destination path on the managed node.
For example, to copy a file named example.txt
from the control node to the /tmp
directory on the managed node, you can use the following task:
- copy:
src: example.txt
dest: /tmp/example.txt
Copying with Permissions
By default, the copy
module will preserve the file permissions from the source file. However, you can also explicitly set the permissions using the mode
parameter:
- copy:
src: example.txt
dest: /tmp/example.txt
mode: "0644"
In this example, the copied file will have permissions set to rw-r--r--
(644 in octal).
You can also use symbolic notation to set the permissions:
- copy:
src: example.txt
dest: /tmp/example.txt
mode: u=rw,g=r,o=r
This will set the permissions to rw-r--r--
.
Copying with Owner and Group
To set the owner and group of the copied file, you can use the owner
and group
parameters:
- copy:
src: example.txt
dest: /tmp/example.txt
owner: myuser
group: mygroup
This will set the owner to myuser
and the group to mygroup
for the copied file.
By understanding how to use the copy
module in Ansible, you can ensure that files are copied to the target hosts with the appropriate permissions, owner, and group. This is crucial when working with sensitive files or ensuring that the copied files have the correct access rights.