Sandro21
Sandro21

Reputation: 311

Copy certain Files from a File that contains the specific Filenames with Ansible

I have a file which contains different filnames. What filenames are in that file, changes every time i run the playbook.

Though I found only ways to either copy all files in a directory or copy certain files that are defined static.

filenames.txt:

file1
file4

Directory that contains the files:

file1
file2
file3
file4
file5

My Plan was to create a variable in my vars sheet in which I save the file and then use it in my role. copy-files: path/filenames.txt

Role to copy the files:

---
- name: Copy Files 
  copy:
    src: "{{ item }}"
    dest: "{{path2}}" 
  with_fileglob:
   - "/pathtofiles/{{copy-files}}"

Sadly this doesen't work. Does somebody else know a different approach?

Upvotes: 0

Views: 1031

Answers (1)

JGK
JGK

Reputation: 4178

When I understand you right, you want to copy the files, listed in path/filenames.txt. You can do it with the following task:

- name: Copy Files to /tmp
  copy:
    src: "{{ item }}"
    dest: "{{ hqlname_sys2 }}"
  loop: "{{ lookup('file', 'path/filenames.txt').split('\n') }}"

The contents of path/filenames.txt is read with the lookup file plugin into a string and that string is splitted by the split function on the '\n' delimiter, so that you get an array with of filenames which is passed to the loop.

Upvotes: 2

Related Questions