Writing

When an Ansible run fails halfway: rolling back from a CI pipeline

/9 min read/Reliability/#ansible/#automation/#ci/#configuration-management/#sre

The last post moved Ansible runs into a scheduled CI pipeline: check mode on a schedule, applies started by hand from main, promoted dev, stg, prd. It skipped the uncomfortable part. What happens when a prd apply fails on host 14 of 40, and the first 13 already have the new config?

This post is about that moment, and about the work you do beforehand so it is boring.

1. Ansible does not roll back

Ansible runs tasks in order and stops a host at the first failure. It does not record what it changed, and it does not undo anything. After a failed run, each host is in one of three states: fully changed, not touched, or changed up to the failed task.

So “rollback” in Ansible means one thing: run the playbook again with the old desired state. Everything else in this post is about making that second run safe and fast, and about the cases where the old desired state is not enough.

2. Fail small

The cheapest rollback is the one you do on two hosts instead of forty. In the play:

- hosts: "{{ target }}"
  serial:
    - 1
    - 5
    - "25%"
  max_fail_percentage: 0

The first batch is a single host. If it fails, the play stops there. max_fail_percentage: 0 stops the play after any batch that has a failed host, so a bad change does not keep rolling out while you read the log.

Two more settings help:

  • any_errors_fatal: true on plays where hosts must stay consistent with each other (for example, a cluster that expects the same config everywhere). It stops all hosts as soon as one fails, not at the end of the batch.
  • A verification task at the end of the role that fails loudly if the service is not healthy. A run that “succeeds” while the service is down is worse than a run that fails. The host tuning post has examples of checking live state rather than trusting that the task ran.

3. Don’t write a broken file in the first place

Many bad changes are a config file with a typo. The template and copy modules take a validate command that runs against the new file before it replaces the old one:

- name: sshd config
  ansible.builtin.template:
    src: sshd_config.j2
    dest: /etc/ssh/sshd_config
    mode: "0600"
    validate: /usr/sbin/sshd -t -f %s
    backup: true
  notify: reload sshd

- name: sudoers drop-in
  ansible.builtin.copy:
    src: ops-sudoers
    dest: /etc/sudoers.d/ops
    mode: "0440"
    validate: /usr/sbin/visudo -cf %s

If validation fails, the task fails and the old file stays in place. For sshd and sudoers this is the difference between a failed run and losing access to the host.

backup: true keeps a timestamped copy of the previous file next to it. It is not a rollback plan (the next section is), but it lets you see exactly what changed on a host, and restore one file by hand in an emergency.

4. Per-host recovery with block and rescue

For a change that has a known good fallback, put the risky part in a block with a rescue:

- name: Apply new service config
  block:
    - name: Render config
      ansible.builtin.template:
        src: app.conf.j2
        dest: /etc/app/app.conf
        backup: true
      register: app_conf

    - name: Restart and wait for health
      ansible.builtin.systemd:
        name: app
        state: restarted
      when: app_conf.changed

    - name: Health check
      ansible.builtin.uri:
        url: http://localhost:8080/health
        status_code: 200
      retries: 10
      delay: 3
      register: health
      until: health.status == 200

  rescue:
    - name: Restore previous config
      ansible.builtin.copy:
        src: "{{ app_conf.backup_file }}"
        dest: /etc/app/app.conf
        remote_src: true
      when: app_conf.backup_file is defined

    - name: Restart with previous config
      ansible.builtin.systemd:
        name: app
        state: restarted

    - name: Fail the run so CI shows it
      ansible.builtin.fail:
        msg: "New config failed health check, previous config restored"

Two things matter here. The rescue ends with fail, so the host still counts as failed and serial stops the rollout. Without it, Ansible treats a rescued host as fine and moves on to the next batch. And the rescue only knows how to undo what the block did, so keep blocks small and specific. A rescue that tries to undo a whole role is a second, untested playbook.

5. The normal rollback: revert and re-run

For most failures the right move is:

  1. Stop. If the pipeline is still running, cancel it. With serial and max_fail_percentage: 0 it has usually stopped on its own.
  2. git revert the change on a branch and open a pull request. Say in the title that it is a rollback, so the reviewer knows to be quick rather than thorough.
  3. Merge, run check mode with --diff against the affected environment, and read the diff. It should show the hosts that got the bad change going back, and nothing else.
  4. Apply through the same pipeline, to the same --limit as the failed run.

This keeps the rule from the last post: only reviewed code from main is applied to prd. The revert is a normal change, with a record of who started it and what it ran.

It is tempting to skip the pipeline and run the old commit by hand from a laptop. Don’t. The laptop has a different Ansible version, different collections, maybe a different inventory, and nobody will know what it ran. If the pipeline is the thing that is broken, that is a separate problem (section 7).

6. What a revert does not undo

Re-applying the old desired state only works if the old roles describe everything the new ones changed. Often they don’t:

  • Added lines and files. If the change added a line with lineinfile or dropped a new file into /etc/sysctl.d/, the old role simply doesn’t mention it. Reverting removes the task, not the line. The line stays.
  • Packages. The old role says “install version X”. It does not say “remove the package the new role added”.
  • Kernel parameters and GRUB. Some settings only take effect after a reboot, and reverting the file does not undo the boot you already did. If the new kernel command line was applied and the host rebooted, the revert needs another reboot too.
  • Data changes. Schema migrations, deleted directories, rotated keys. These need their own plan and are usually out of scope for a host config playbook anyway.

The fix is to write the change so that a revert has something to work with. When you add something, also think about how you remove it:

- name: Extra sysctl file
  ansible.builtin.copy:
    src: 90-extra.conf
    dest: /etc/sysctl.d/90-extra.conf
  when: extra_sysctl_enabled | bool

- name: Remove extra sysctl file when disabled
  ansible.builtin.file:
    path: /etc/sysctl.d/90-extra.conf
    state: absent
  when: not (extra_sysctl_enabled | bool)

Now rolling back is a variable change, extra_sysctl_enabled: false, and the removal is tested code instead of a manual step during an incident. For bigger changes, ship the feature behind a variable that defaults to off, turn it on per environment, and keep the “off” path in the role for at least one release.

Check mode with --diff helps here too. Before the revert, run it and look for hosts where the diff is empty but you know the change landed. That usually means one of the cases above.

7. An emergency path that still runs reviewed code

Sometimes waiting for a pull request is too slow, or the bad change broke something the pipeline depends on. Have the emergency path decided in advance, not invented during the incident:

  • Apply a known good tag. Tag main after each successful prd apply. The manual apply job can take a tag as input instead of main, so “re-apply the last known good” is one click and still runs code that was reviewed and ran before. Follow up with the proper revert on main, or the next scheduled check will report drift against the bad commit.
  • A break-glass runbook for when CI is down. Who can run Ansible by hand, from where, with which pinned versions, and how they record what they ran. Keep the prd key out of this path unless the runbook says how it is fetched and rotated afterwards.

Both of these should be rare. If they are used often, the normal path is too slow and that is the thing to fix.

8. Check that you are back

A rollback is done when the hosts are healthy and the config matches main, not when the pipeline is green:

  • Run check mode with --diff on the whole environment. The result should be zero changes. This is the same drift check that runs on a schedule, and it is the quickest way to find a host that a partial run left in the middle.
  • Look at the service dashboards, not only the Ansible output. Ansible tells you the file is right; the dashboards tell you the service is.
  • Compare the failed hosts and the untouched hosts. They should now look the same.

Then write down what happened while it is fresh. Most of the useful fixes are small: a missing validate, a rescue that should have existed, a “remove when disabled” task nobody wrote.

9. Changes and trading hours

All of this assumes the rollback can happen when it needs to. For prd hosts that serve trading, the apply job checks the change window before it runs (covered in the last post). Decide in advance whether a rollback is allowed to skip that check. A rollback during market hours carries its own risk, and sometimes leaving the first few failed hosts out of rotation until the window opens is safer than touching more hosts. That is a decision for the runbook, made calmly, not for the person on call at the time.

Checklist

  • serial starts with one host; max_fail_percentage: 0
  • Roles end with a check of live service health
  • validate on config files that can lock you out (sshd, sudoers) or break a service
  • backup: true on files you may need to compare or restore by hand
  • block/rescue for risky steps, and the rescue ends with fail
  • Rollback is git revert through the same pipeline, check mode with --diff first
  • New files, lines and packages have a matching “remove when disabled” path
  • Changes that need a reboot have a rollback plan that includes the reboot
  • Main is tagged after each good prd apply; the apply job can take a tag
  • Break-glass runbook written before it is needed
  • After a rollback, a full check mode run shows zero changes

References