How to tell what directory was created by ansible's unarchive module?
The unarchive module does have the option to list the files - list_files
. The output can be registered, and usually the first value in the array is the directory name.
The following worked for me:
- name: Extract files
unarchive:
src: /tmp/my_archive.tar.gz
dest: /mydir
remote_src: yes
list_files: yes
register: archive_contents
archive_contents.files[0]
will have your top level directory.
Update: see answer from @vinayak-thatte for correct answer.
Unarchive module doesn't know what's inside the archive – it just places all archive content into dest
folder.
If you know in advance that there is or there may be a single folder inside the archive, you can make some test like this:
- name: Get dir 1 - fast - when you are sure that there is one and only one subfolder
shell: tar tf file.tgz | head -1 | sed -e 's/\/.*//'
changed_when: false
register: tar_test
- debug: 'msg="Subfolder: {{tar_test.stdout}}"'
- name: Get dir 2 - slow - when you dont sure
shell: tar tf file.tgz | sed -e 's/\/.*//' | sort | uniq
changed_when: false
register: tar_test
- debug: 'msg="Subfolder: {{tar_test.stdout}}"'
when: tar_test.stdout_lines | count == 1
- debug: msg="No subfolder!"
when: tar_test.stdout_lines | count > 1
First method is quicker than second, but it checks only one line of archive file listing – so you must me sure that there is only one subfolder inside.
Second method checks all paths in the archive and collects distinct names in the archive "root" – so if there is only one match (count == 1) it is very likely to be subfolder (or single file in the archive :-/), otherwise there are many entries in the archive "root".