How to extract an archive in Ansible?
I'm going to show you a live Playbook and some simple Ansible code.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Ansible extract an archive
Today we're talking about the Ansible module unarchive.
The full name is ansible.builtin.unarchive, which means that is part of the collection of modules "builtin" with ansible and shipped with it.
It's a module pretty stable and out for years.
It works in a different variety of operating systems.
It unpacks one archive after (optionally) copying it from the local machine
It can handle .zip files using unzip as well as .tar, .tar.gz, .tar.bz2, .tar.xz, and .tar.zst files using gtar. It requires zipinfo,gtar and unzip command on target host.
Please note that it requires a tarball (.tar archive) for the Unix file format.
For Windows targets, use the community.windows.win_unzip.
Parameters
- src _string_ - path
- dest _string_ - path
- remote_src _boolean_ - no/yes
- validate_certs _boolean_ - no/yes (https only)
- include/exclude _list_ - directory and file entries
- extra_opts _string_ - command-line options
- keep_newer _boolean_ - no/yes
- mode/owner/group - permission
- setype/seuser/selevel - SELinux
The parameter list is pretty wide but this three are the most important options.
The only mandatory parameters are "src" and "dst" which are the source and destination paths. The "src" is quite special because is supposed to be a local path on the Ansible controller.
We could switch to a remote path enabling the "remote_src" properties.
In the "src" parameter we could also enter a URL, so the archive is going to be downloaded before being expanded.
Other useful parameters are "include" and "exclude" that allows us to specify a subset of the archive to extract, specifically a list of inclusion or exclusion files or directories.
Just in case we need some extra command-line options we could specify in the "extra_opts" parameter.
If the files are already present on the target machine the default behavior is to not replace existing files that are newer than files from the archive, you could override enabling the "keep_newer" parameter.
Let me also highlight that we could also specify some permissions or SELinux properties.
## Playbook
Let's jump in a real-life playbook to extract an archive in Ansible Playbook with Ansible.
- unarchive.yml
``yaml
---
- name: unarchive module Playbook
hosts: all
become: false
vars:
myurl: "https://github.com/lucab85/ansible-pilot/archive/refs/heads/master.zip"
tasks:
- name: extractor presents
ansible.builtin.yum:
name:
- unzip
- tar
state: present
become: true
- name: extract archive
ansible.builtin.unarchive:
src: "{{ myurl }}"
dest: "/home/devops/"
remote_src: true
validate_certs: true
``
[code with ❤️ in GitHub](https://github.com/lucab85/ansible-pilot/tree/master/extrac