Ansible: copy a directory recursive

Posted by ads' corner on Thursday, 2019-04-11
Posted in [Ansible][Linux]

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
- 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
- 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 …


Categories: [Ansible] [Linux]