ofek ofek
ofek ofek

Reputation: 1

Find and copy files with ansible

I want to make a script with ansible, to search on folder "/software" all the files, that were edited in the last day, then move them to "/tmp"

This my code so far (redhat 7.4):

 - name: recurse path
   find:
     path: /software
     recurse: yes
     file_type: file
     age: 1d
   register: files
 - name: copy files to tmp
   copy:
     src: ~/{{files}}
     dest: /tmp

I get the error:

an exeption occurred during task execution ... could not find or access '~{u'files': []}, u'changed': False, 'failed': False, u'examined': 4....

The folders have full access, so I dont think its permissions.

What am I doing wrong?

Upvotes: 0

Views: 6026

Answers (1)

zigarn
zigarn

Reputation: 11625

As documented, the returned value of the find module is an object containing the list of found files under the files keyword.

You cannot use it directly: copy module takes only 1 file or folder as src, so you have to loop over all the files:

- name: check the content and structure of the variable
  debug:
    var: files
- name: copy files to tmp
  copy:
    src: "{{item.path}}"
    dest: /tmp
  with_items: "{{files.files}}"

It's always a good practice to debug a var after register while developing to check it's structure (so you can find how to use it) and it's content (in your case, looks like the file list is empty).

BTW: you need to know that the find module search on the remote host but, by default, the copy module copies from the ansible executor machine, so in your case, the src may not exists! So if you are copying from local to remote, simply add delegate_to: localhost and run_once: yes to your find task, otherwise you need to use the remote_src: yes parameter on the copy task.

Upvotes: 3

Related Questions