Search code examples
dateansiblearchive

ansible - archive files, with a dated filename, by archive date


I want to archive all files, containing a date in their names, present in a same folder, in the same archive by date with Ansible.

Let me explain:

Files can be of this type: (attention the date can be separated by dashes or underscores)

/app/logs/app.log
/app/logs/app.log.2018-12-04
/app/logs/app.log.2018-12-05
/app/logs/batch.log
/app/logs/batch.log.2018-12-04
/app/logs/batch.log.2018-12-05
/app/logs/web.log
/app/logs/web.log.2018_12_04
/app/logs/web.log.2018_12_05

I want archive files, with ansible, containing a date like this:

/app/logs/20181204.tar.gz
/app/logs/20181205.tar.gz

For the moment I search files :

- name: Search files
  find:
    paths: "/app/logs/"
  register: files

I try to build new dictionary :

- set_fact:
  file:
    - "name": "{{ item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') }}"
      "path": [ "{{ item.path }}" ]
  loop: "{{ files.files }}"
  when: item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') != ''

And archive my files, but my var file contains only one file

- name: archive logs
  archive:
    path: "{{ item.path }}"
    dest: "/app/logs/{{ item.name }}.tar.gz"
  with_items: "{{ file }}"

Thanks for your help


Solution

  • And archive my files, but my var file contains only one file

    That's because you're setting the variable file to a single value:

    - set_fact:
      file:
        - "name": "{{ item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') }}"
          "path": [ "{{ item.path }}" ]
      loop: "{{ files.files }}"
      when: item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') != ''
    

    Just putting set_fact in a loop doesn't change the fact that you are setting file to the single value {{ item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') }}.

    If you want the result of your set_fact task to be a list, you need to build a list. Something like this might work:

    - set_fact:
        files_list: "{{
          (files_list|default([])) +
          [{
          'name': item.path | basename | regex_replace( '[A-Z-_.a-z]' , ''),
          'path': item.path
          }]
          }}"
        loop: "{{ files.files }}"
        when: item.path | basename | regex_replace( '[A-Z-_.a-z]' , '') != ''
    

    That will create the files_list list variable by appending a dictionary to it for each iteration of your loop.