Skip to content

Ansible: copy a directory recursive

Recently I was looking for a way to copy a directory with all subdirectories, using Ansible. For reasons beyond this post I couldn't use the synchronize (rsync) module. So I had to find a way to copy everything with basic Ansible steps.

 

That is possible, but it requires several steps, and it is very slow. Up to the point where it is not practical to use this approach for more than a few files and directories. Nevertheless, before moving on to another solution, I thought I document the steps here.

The with_filetree lookup is used to first create all directories and subdirectories, and then in a seond step copy all files. This has to be split into two (and possibly more steps, as symlinks are not handled here) steps, because copying the files requires the "item.src" variable - which is not available for directories.

First create all subdirectories:

- name: Create directories
  file:
    path: "/path/to/remote/directory/{{ item.path }}"
    state: directory
    mode: '{{ item.mode }}'
  with_filetree:
    - "/path/to/local/directory"
  when: item.state == 'directory'
  loop_control:
    label: "{{ item.path }}"

 

After all directories are created, all files can be copied:

- name: Copy files
  copy:
    src: "{{ item.src }}"
    dest: "/path/to/remote/directory/{{ item.path }}"
    mode: "{{ item.mode }}"
  with_filetree:
    - "/path/to/local/directory"
  when: item.state == 'file'
  loop_control:
    label: "{{ item.path }}"

 

Maybe add "owner" and "group" options as well ...

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.
Form options