Ansible Recursive Directory Copy

file module is not for copying the files, but for setting attributes of files on the target.

copy module is for copying.


Providing some additional information to the accepted answer..

Recursive copy using directory paths has the following disadvantages:

  • you cannot get changed state information per file copied
  • so --check and --check --diff flags won't show anything
  • you cannot include/exclude specific files/directories to/from the recursion
  • performing corrective changes after the bulk copy will never produce a state with changed=0 and could also affect files that already existed on remote host.

There seems to be a more powerful way to perform a recursive copy, which is to use with_filetree combined with when

- name: "create-remote-dirs"
  file:
    path: /dest/dir/{{item.path}}
    state: directory
    mode:  '0775'
  with_filetree: sourceDir/
  when: item.state == 'directory'
- name: "copy-files"
  copy:
    src: "{{item.src}}"
    dest: /dest/dir/{{item.path}}
    mode:  '0744'
  with_filetree: sourceDir/
  # combinations of 'is' and 'is not' can be used below.
  when: item.state == 'file' 
        and item.path is not search("excludedDir/*")
        and item.path is not search("*.bak")

Tags:

Ansible