How can I pick up name of file in archive and save it as variable?

Viewed 88

I hope I can explain this clearly, as I encounter one problem and need to use something apart from simply mv (rename) module in Ansible.

I have a task and one of the problem I encounter is that I need to download one file, which has name file-latest.zip. When I unarchive it, first folder I see will be name file-1.2.20 for example. Now, of that name depends how I am going to organize many files and templates. Next time, behind this file-latest.zip will be updated version or file-1.2.21, which I never know.

I would like somehow, when I unarchive, to save it in some variables latest name of that file and then to work further with that variable, but I am not too sure how to figure this out.

I am very beginner in this and this gave me so many thoughts and could not go around and find solution.

1 Answers

One way, if you do have the folder as an unique direct child of your archive would be to use the parameter list_files: true, and gather the directory.

Given a file file-latest.zip:

$ unzip -l file-latest.zip 
Archive:  file-latest.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  06-13-2022 15:19   file-1.2.21/
        0  06-13-2022 11:01   file-1.2.21/foo
        0  06-13-2022 15:19   file-1.2.21/baz
        0  06-13-2022 15:19   file-1.2.21/bar
---------                     -------
        0                     4 files

The two tasks:

- unarchive:
    src: file-latest.zip
    list_files: true
    dest: /tmp
  register: zip_content

- debug:
    var: zip_content.files[0][:-1]

Would unarchive the zip on the target node and yield:

TASK [unarchive] *************************************************************
changed: [localhost]

TASK [debug] *****************************************************************
ok: [localhost] => 
  zip_content.files[0][:-1]: file-1.2.21

From there, you can use it as is or register it in a variable using the set_fact module, e.g.:

- set_fact:
    archive_version_name: "{{ zip_content.files[0][:-1] }}"
Related