Ansible for Archives
Three modules move archives around: community.general.archive creates them on the managed node, ansible.builtin.unarchive extracts them, and ansible.builtin.fetch copies files from the node back to control.
yaml - community.general.archive: path: /etc/httpd/conf a file, a directory, a glob or a list dest: /root/httpd-conf.tar.gz format: gz bz2, xz, zip, tar - ansible.builtin.fetch: src: /root/httpd-conf.tar.gz dest: "backups/{{ inventoryhostname }}-httpd-conf.tar.gz" flat: true
Without flat: true, fetch builds dest/<host/<full path, which keeps hosts apart but rarely matches the file name a task asks for. With flat, put the host name in the file name yourself or every host overwrites the same file.
archive with remove: true deletes the sources after archiving, which is how log rotation tasks are phrased ("archive and remove the originals"). excludepath skips files.
yaml - ansible.builtin.unarchive: src: files/site.tar.gz on control: copied first dest: /var/www/html - ansible.builtin.unarchive: src: http://utility/collections/ansible-posix-1.6.2.tar.gz dest: /opt/posix remotesrc: true already on the node or a URL
dest must already exist: create it with file: state: directory first. creates: makes a re-run skip extraction when a given file exists. unarchive needs tar/unzip on the node.
Checking your work. List an archive without extracting it: ansible prod -m command -a 'tar tzf /root/httpd-conf.tar.gz' (tjf for bzip2). On control, ls backups/ should show one file per host and nothing for hosts outside the group. A second run of the playbook should report ok for archive and unarchive when nothing changed; if unarchive reports changed every time, add creates: pointing at a file the archive contains.
Pitfalls. Mixing up which side the file is on: remotesrc: true means "the archive is on the managed node (or a URL)". Forgetting the format (default is gz) when the task names .tar.bz2. Archiving with command: tar, which changes every run and is not idempotent. Writing the backup to every host when the task names one group.