13

In my files directory I have various files, with a similar name structure:

data-example.zip
data-precise.zip
data-arbitrary.zip
data-collected.zip

I would like to transfer all of these files in the /tmp directory of my remote machine using Ansible without specifying each file name explicitly. In other words I would like to transfer every file that stars with "data-".

What is the correct way to do that? In a similar thread, someone suggested the with_fileglob keyword, - but I couldn't get that to work. Can someone provide me an example on how to accomplish said task?

Kyu96
  • 1,159
  • 2
  • 17
  • 35

2 Answers2

38

Method 1: Find all files, store them in a variable and copy them to destination.

- hosts: lnx
  tasks:
    - find: paths="/source/path" recurse=yes patterns="data*"
      register: files_to_copy
    - copy: src={{ item.path }} dest=/dear/dir
      owner: root
      mode: 0775
      with_items: "{{ files_to_copy.files }}"

Use remote_src: yes to copy file in remote machine from one path to another.

Ansible documentation

Method 2: Fileglob

Fileglob allows using patterns to match files and directories

- name: Copy each file over that matches the given pattern
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: "root"
    mode: 0600
  with_fileglob:
    - "/playbooks/files/fooapp/*"

Ansible documentation

elchusco
  • 3
  • 3
deepanmurugan
  • 1,815
  • 12
  • 18
  • 2
    Thanks for the reply. It seems that `with_fileglob` is suitable for most cases. However I don't think there is a way to do this kinda pattern matching directly on the remote machine? (For example if you want to copy all files that match the pattern from one place on the remote machine to another place on the remote machine? – Kyu96 May 31 '20 at 13:10
  • 1
    Is the source and destination path both on remote machine? – deepanmurugan May 31 '20 at 13:13
  • 1
    By default I assume the src path always refers to the local machine, not to the remote. – Kyu96 May 31 '20 at 13:20
  • 1
    Yes source path refers to the local. You want to copy files from remote machine A to remote machine A or remote machine A to remote machine B? – deepanmurugan May 31 '20 at 13:25
  • 3
    `with_fileglob` is used to copy files from the ansible server to the remote server. If you want to copy files inside the remote server, you need to use the first method. – robe007 Nov 02 '20 at 06:56
  • It's important to add that `with_fileglob` will search files on the control host, while `find` will search on the target host. – reinierpost Apr 21 '21 at 12:52
19

Shortly after posting the question I actually figured it out myself. The with_fileglob keyword is the way to do it.

- name: "Transferring all data files"
  copy:
    src: "{{ item }}"
    dest: /tmp/
  with_fileglob: "data-*"
Kyu96
  • 1,159
  • 2
  • 17
  • 35