Alvaro Niño
Alvaro Niño

Reputation: 567

Ansible create tar.gz with archive module from a list

I'm trying to find files older than one day in Ansible and after that, create a tar.gz of those files, I've tried archive module, although it is creating only a tar of the last element in the list. Is there any way to create tar.gz including all files?

Below is my script:

  - name: Check all files
    find: paths=/myfiles
          file_type=file
          age=1
          age_stamp=mtime
    register: files
    failed_when: files.matched < 10

  - name: Remove previous tarFile
    file: path=/tmp/test.tar.gz
          state=absent

  - name: compress all the files in tar.gz
    archive: path="{{ item.path }}"
             dest=/tmp/test.tar.gz
             format=gz
    with_items:
        "{{ files.files }}"

Upvotes: 2

Views: 14088

Answers (2)

i have created multiple zip files using below method.

- name: 'Create zip archive of {{ date_input }} NMON HTML files'
  archive:
    path: /tmp/{{ inventory_hostname }}_*.html
    dest: /tmp/NMON-{{ inventory_hostname }}.zip
    format: zip
  when: option == "5"
  delegate_to: localhost

Upvotes: 0

techraf
techraf

Reputation: 68529

it is creating only a tar of the last element in the list

It is creating and overwriting /tmp/test.tar.gz for each file in the loop. When you check, you see only the last one.


If you look at the archive module docs, you will see:

path Remote absolute path, glob, or list of paths or globs for the file or files to compress or archive.

So you can provide the list of files as a value for the path parameter:

- name: compress all the files in tar.gz
  archive:
    path: "{{ files_to_archive }}"
    dest: /tmp/test.tar.gz
    format: gz
  vars:
    files_to_archive: "{{ files.files | map(attribute='path') | list }}"

Upvotes: 4

Related Questions