Working with Ansible archive module
Until version 2.3, Ansible didn’t support an Archive module(It was available in the developer edition for some time though). Before that, we had to use the shell module or command module to zip a directory in Ansible.
From 2.3 you can use the Ansible archive module to compress the files or folders into ‘.zip’, ‘.gz.’ and ‘bz2’ format.
Note: The files to be compressed should be available on the remote servers.
Note: The target servers should have the packages for tar file, bzip2, gzip, zipfile installed on them.You can have a separate task for checking and installing the packages.
Ansible zip file
To zip a file, we need at least one parameter, the file which is to be archived. The absolute path of the input file is to be given to the ‘path‘ parameter. This is the path on the target machine.
The destination path, if not specified will be the path of the input file itself. Both the target path and the filename can be set using the ‘dest‘ parameter.
You can also give the archive format you want. The default value is ‘.gz’. You can specify the ‘.zip’, ‘.gz’ or ‘.bz2’ against the ‘format’ parameter.
The following task will zip the file zipfile.txt to zipfile.txt.zip file.
- hosts: all tasks: - name: Ansible zip file example archive: path: /Users/mdtutorials2/Documents/Ansible/zipfile.txt
ACM:Ansible ACM$ ls -lrt total 88 -rw-r--r-- 1 root staff 168 Jul 29 15:54 zipfile.txt -rw-r--r-- 1 root staff 160 Aug 3 06:54 zipfile.txt.zip
If you need to change the output file name or path, then you can use the ‘dest‘ parameter to set them both. The following task will create the ‘zipfile2.zip’ in the mentioned path.
- hosts: all tasks: - name: Ansible zip file with path example archive: path: /Users/mdtutorials2/Documents/Ansible/zipfile.txt dest: /Users/mdtutorials2/Documents/zipfile2.zip format: zip
Ansible zip multiple files
You can give multiple files to be compressed as input, against the path parameter. The ‘dest’ parameter should be set to the output filename.
- hosts: all tasks: - name: Ansible zip multiple files example archive: path: - /Users/mdtutorials2/Documents/Ansible/zipfile.txt - /Users/mdtutorials2/Documents/Ansible/zipfile2.txt - /Users/mdtutorials2/Documents/Ansible/zipfile3.txt dest: /Users/mdtutorials2/Documents/multi.zip format: zip
Note: If you do not give the dest parameter while giving multiple files as input, then you will get the following error during execution.
"Error, must specify \"dest\" when archiving multiple files or trees"
Ansible zip directory
You can also zip entire directory using the Archive module. As with files you just need to set the directory name against path parameter. The following example will zip the test1 directory to direc.zip.
- hosts: all tasks: - name: Ansible zip directory example archive: path: - /Users/mdtutorials2/Documents/Ansible/test1 dest: /Users/mdtutorials2/Documents/Ansible/direc.zip format: zip