Chapter 10: Automating Linux Administration Tasks

Archiving and restoring files

Backups, releases and log collections all end up as archives. Ansible has one module to pack files on a managed host and another to unpack them, and with a few options both behave predictably on every run. A backup is only useful if you can restore it, so you will also check that a restore gives back the same files.

Two modules, two directions

community.general.archiveansible.builtin.unarchive
DoesPacks files into an archiveUnpacks an archive into a directory
SourceFiles on the managed hostAn archive on the control node, or on the managed host with remote_src: true
ResultAn archive file on the managed hostFiles in an existing directory on the managed host
Formatsgz (default), bz2, xz, zip, tartar (any of those compressions) and zip

archive is in the community.general collection, which is installed on workstation. unarchive is part of ansible-core. Both need the archiving tools on the managed host, such as tar and gzip, which every RHEL system has.

Create an archive

- name: The release is packaged
  community.general.archive:
    path: /srv/release/
    dest: /tmp/release.tar.gz
    format: gz
    mode: "0644"

The trailing slash decides the layout

pathThe archive containsExtracted into /srv/restored
/srv/releasethe directory release/ and its files/srv/restored/release/version.txt
/srv/release/only the directory's contents/srv/restored/version.txt

Decide where the files must land after a restore, then choose the slash.

Extract an archive

- name: The restore directory exists
  ansible.builtin.file:
    path: /srv/restored
    state: directory
    mode: "0755"

- name: The release is restored
  ansible.builtin.unarchive:
    src: /tmp/release.tar.gz
    dest: /srv/restored
    remote_src: true
    owner: root
    group: root

Check the restore, not just the archive

An archive that exists is not proof of anything. Check that the restored files match the originals in content and in access:

[student@workstation ~]$ ssh devops@servera.lab.example.com \
  'cmp /srv/release/version.txt /srv/restored/version.txt && stat -c "%a %U:%G" /srv/restored/version.txt'
644 root:root

cmp prints nothing and succeeds when two files are identical. If you put checks like these in a playbook, add changed_when: false: they only read, so they must not inflate the change count.