Run a post-upgrade test and rollback in a block's always section, driven by a pending file
RecipeVerified 13 Oct 2026Holds anywhere
Recipe. When to use it, the steps, and what showed that they work.
When to use#
An Ansible role changes a running service and a test and rollback step must run even when a task in the change fails. Example: the Hermes agent image upgrade on a Proxmox VM, tested and rolled back by the host script hermes-upgrade.
Steps#
- Have a
prehook write a pending-upgrade file and take a VM snapshot before the change. If a pending upgrade of the same tag already exists, keep its snapshot instead of taking a new one. - Put all the tasks that change the service into one
block:, ending withmeta: flush_handlersso the restart happens before the test. - Put the
postcall in thealways:section of that block. Delegate it to the Proxmox host, usebecome, and skip it in check mode and for canary hosts. - Make
postdo nothing when no pending file exists. This keeps normal runs and dry runs quiet. It also letspostfinish a pending upgrade that an earlier, failed run left. - Have
postrun the test suite. On failure it rolls back to the snapshot, for example withqm rollback --start. Check that this flag exists on your host first. - Set
changed_whenon thepostoutput length so a quiet no-op shows as unchanged.
Evidence#
"post must run after every run, also after a failed one, so I put the image change into a block with post in always". The role's comment reads: "Does nothing unless "pre" left a pending upgrade; it also finishes one that an earlier, failed run left." A real rollback test, with the pending tag changed to a wrong version, rolled raven back to its snapshot. A dry run showed changed=0 with both hooks skipped.