Question

How can I use Ansible to copy a directory while keeping its permissions?

Answer and Explanation

To copy a directory with its permissions using Ansible, you should use the synchronize module. This module is specifically designed for synchronizing directories between the Ansible control machine and remote hosts, and it preserves file permissions.

Here’s how you can achieve this:

1. Using the `synchronize` module:

- The `synchronize` module uses rsync under the hood and has options to control how files are copied. The key option here is mode: push or mode: pull depending on where the source directory is.

2. Example Ansible task:

- name: Copy a directory with permissions
  synchronize:
    src: /path/to/source/directory/
    dest: /path/to/destination/directory/
    mode: push
    rsync_opts:
      - "--perms"
      - "--recursive"
      - "--times"

Explanation of the options:

- `src`: specifies the source directory path on the ansible controller node.

- `dest`: Specifies the destination directory path on the target node.

- `mode: push`: Indicates that the copy should be pushed from the control machine to the target machine. You can use `mode: pull` if the source is on the remote machine and needs to be copied to control machine.

- `rsync_opts`: rsync options, where

  • "--perms": preserves permissions
  • "--recursive": recursively copies directories
  • "--times": preserves modification times

Note: Do not forget to add a trailing slash to your directory paths.

3. Using `delegate_to: localhost` for local file copies:

- If you need to copy directories on the same host where Ansible is running, delegate the task to localhost.

- name: Copy a directory on localhost with permissions
  synchronize:
    src: /path/to/local/source/directory/
    dest: /path/to/local/destination/directory/
    mode: push
    rsync_opts:
      - "--perms"
      - "--recursive"
      - "--times"
  delegate_to: localhost

4. Important Considerations:

- Make sure the target directory exists, and the user running the ansible command has the permissions to write on the directory.

- Always test your playbook first with a small directory or using --check flag to avoid unintended side-effects.

By using the `synchronize` module with these rsync options, you can reliably copy directories with their permissions intact using Ansible.

More questions