Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible copy files with wildcard?

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?

like image 280
Kyu96 Avatar asked May 31 '20 12:05

Kyu96


2 Answers

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: file_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

- 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

like image 115
deepanmurugan Avatar answered Oct 12 '22 13:10

deepanmurugan


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-*"
like image 21
Kyu96 Avatar answered Oct 12 '22 14:10

Kyu96