Tons of new funtionality in Massdriver! We're demoing a new feature everday until Christmas.

Check out the advent calendar here
Engineering
How to Automatically Roll Back a Failed Terraform Apply

How to Automatically Roll Back a Failed Terraform Apply

Terraform and OpenTofu have no rollback command. How teams roll back failed infrastructure deployments today, where those scripts break, and how to roll back to the last good deployment automatically.

Cory O'Daniel7 min
Share

Your application team has kubectl rollout undo. Helm has helm rollback. Your CD tool has a big friendly button that puts the last image back. Then somebody bumps the task memory on the app's service module, terraform apply dies halfway through with a quota error, and the rollback plan is a person in Slack asking "what was it set to before?"

Terraform and OpenTofu have no rollback command. An apply is not a transaction. Resources that were created before the error stay created. The state file records what actually happened, so there is nothing to undo. The only way back is forward: plan and apply the configuration that worked last time.

That sounds easy until you try to say precisely what "the configuration that worked last time" means.

What a rollback has to put back

To re-apply the last good deployment of a piece of infrastructure, you need all of it:

  • the exact module version that was applied, not the one on main today
  • the exact variable values, including the ones that came from a tfvars file, a CI secret, and a -var flag somebody added to the pipeline in 2022
  • the outputs of everything upstream that fed it, such as the VPC ID, the subnet list, and the KMS key, as they were at that time

Miss any one of those and your "rollback" is a brand new change that nobody reviewed, made at the worst possible moment.

How teams roll back failed applies today

I've seen three patterns, and I've built all three.

Git revert and rerun the pipeline. Find the commit that broke things, revert it, wait for CI, approve the plan. This works when the change and the config live in the same repository and the pipeline is fast. It falls over when the variables live somewhere else, when two changes merged since the last good apply, or when the upstream outputs changed in the meantime. It also needs a human awake.

A CI step that runs on failure. Something like on: failure โ†’ check out HEAD~1 โ†’ terraform apply -auto-approve. I love the optimism. HEAD~1 is the previous commit. The last successful apply may be several commits back. If the rollback fails, the same step happily rolls back the rollback. If two pipelines run against the same state, you get a lock fight at best. And the CI runner now holds credentials that can apply anything to production with no approval, which your security team will bring up at some point.

A runbook. A wiki page with the steps above, written for a calm person with context. The person who runs it at 2 a.m. has neither.

All three share a root problem: the record of "what was deployed" is scattered across git history, CI logs, and a state file that only stores the result. Nobody wrote down the deployment as one thing you can point at and say "do that again."

Roll back to the last good deployment, automatically

In Massdriver every deployment is a record. Each PROVISION deployment of an instance keeps the bundle version, the params, and the dependency connections that it ran with. The rollbackDeployment mutation takes a deployment and proposes a new PROVISION with exactly those values. It runs your same Terraform, OpenTofu, or Helm through the same pipeline, with the platform's cloud credentials, so the thing doing the rollback never holds broad cloud credentials itself.

That makes automatic rollback a small event handler. rollback-on-failure is one of the Massdriver automations. It listens for deployment.failed, and when a PROVISION deployment of an opted-in instance fails, it rolls the instance back to its most recent completed PROVISION:

A failed PROVISION of visits-dev-app at v1.4.2 sends deployment.failed to rollback-on-failure, which calls rollbackDeployment on the last completed deployment at v1.4.1 and approves it, so a third deployment restores v1.4.1 with the same bundle version, params, and connections

When it fires, it makes two calls:

  1. rollbackDeployment proposes a new PROVISION deployment with the bundle version, params, and dependency connections of the completed deployment.
  2. approveDeployment approves the proposal, so it runs.

In the instance's deployment history, the rollback is a normal deployment with a ROLLBACK tag, made by the automation's service account, that names the deployment it restores:

Deployment history of visits-dev-app: two provisioning failed deployments with the message Redeploy visits-dev-app with its current params, then a provisioned deployment by Automations tagged ROLLBACK that links Rollback to deployment f6b5c3a62c74

The interesting part is the list of times it does nothing, because that's where the CI script went wrong:

  • The failed deployment is itself a rollback. A failed rollback needs a person. The automation posts a notice that the instance needs attention and stops. No rollback loops.
  • Another deployment of the instance is PENDING, APPROVED, or RUNNING. Someone is already doing something. It stays out of the way.
  • The instance has no completed PROVISION. There is nothing good to go back to.
  • A PROVISION that started after the failed one already completed. Somebody fixed it forward. Going back now would undo their fix.

The event it reacts to

Massdriver sends a signed CloudEvent for every deployment state change through an event destination. A failed deployment looks like this (trimmed):

{
  "type": "deployment.failed",
  "data": {
    "entity": {
      "id": "5c1de0a7-92b4-4f1e-8d3a-6e27c9f0b815",
      "status": "FAILED",
      "action": "PROVISION",
      "version": "1.4.2",
      "message": "Bump the task memory",
      "rollback_of_deployment_id": null
    },
    "metadata": { "credential": "system", "deployment_action": "PROVISION" },
    "attributes": {
      "md-project": "visits",
      "md-environment": "dev",
      "md-component": "app",
      "md-instance": "visits-dev-app",
      "md-bundle": "aws-ecs-service@1.4.2"
    }
  }
}

The destination filters on the Massdriver side, so the automation only gets the events it acts on. This one sends failed PROVISION deployments of opted-in instances, plus the completed rollbacks so it can report how they ended:

mass event destination create \
  --name rollback-on-failure \
  --url https://rollback.example.com/hooks/massdriver \
  --event-type deployment.failed \
  --event-type deployment.completed \
  --condition '.data.metadata.deployment_action == "PROVISION" and .data.attributes["autorollback"] == "true" and (.type == "deployment.failed" or ((.data.entity.message // "") | startswith("Rollback to deployment ")))'

To roll back in one environment only, add --attribute md-environment=prod.

Opt in per component

Nothing rolls back unless you say so. The opt-in is a custom attribute, autorollback=true, set on a component. It applies to the instances of that component in every environment. Create the attribute once at the component scope, with the values true and false, and with Required turned off so components without it stay valid. With the API, that's the createCustomAttribute mutation:

curl https://api.massdriver.cloud/api/v2 \
  -H "Authorization: Bearer $MASSDRIVER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "mutation { createCustomAttribute(organizationId: \"acme\", input: {key: \"autorollback\", scope: COMPONENT, required: false, values: [\"true\", \"false\"]}) { successful messages { field message } } }"}'

The config file is short, and every key is optional:

attribute:
  key: autorollback
  value: 'true'

slack:
  channel: '#deploys'

With a Slack bot token, each rollback gets a notice in that channel, and the result of the rollback, completed or failed, lands as a reply in the notice's thread:

Deployment 5c1de0a7-92b4-4f1e-8d3a-6e27c9f0b815 of visits-dev-app failed. Rollback 9e2f6a1d-3c8b-4d07-a5e2-7b1c0f4d9a36 restores deployment 41b7c2e9-0d5a-4f3b-9e81-2a6d7c5f0b14 (v1.4.1).

The Slack notice in #deploys says deployment 5c1de0a7 of visits-dev-app failed and rollback 9e2f6a1d restores deployment 41b7c2e9 at v1.4.1, and a reply in its thread says rollback 9e2f6a1d completed

Deploy it with the massdriver-rollback-on-failure bundle (Kubernetes) or massdriver-rollback-on-failure-ecs (Amazon ECS with Fargate). The bundle runs the automation and creates the event destination above. Or run the container yourself:

docker run -p 8080:8080 \
  -v "$PWD/config.yaml:/etc/massdriver-automations/config.yaml:ro" \
  -e MASSDRIVER_ORGANIZATION_ID=acme \
  -e MASSDRIVER_API_KEY=md_... \
  -e MASSDRIVER_SIGNING_SECRET=whsec_... \
  -e SLACK_BOT_TOKEN=xoxb-... \
  ghcr.io/massdriver-cloud/massdriver-automations:0.3 run rollback-on-failure

The service account needs instance:propose for the rollback, instance:deploy for the approval, and project:view on the projects to read the deployment history.

Production approvals still apply

If an environment has separation of duty turned on, nobody approves their own proposal, and that includes the service account. The rollback is still proposed, with the right version and params already filled in, and it waits in PROPOSED for a person. The Slack notice says it waits for approval.

I think that's the right default for a lot of production environments. The automation does the part that's slow and error-prone at 2 a.m. (finding the last good deployment and building the exact change), and a person makes the call. Dev and staging can roll back on their own.

What a rollback does not undo

Be honest with yourself about this part before you opt anything in.

A rollback restores the bundle version, the params, and the dependency connections of the completed deployment. It does not restore data. If the failed apply ran a destructive change against a database, re-applying the old config will not bring rows back. It also does not undo changes made outside Massdriver, like the security group rule somebody added in the console during the incident.

The approval pins the instance to the bundle version of the completed deployment and saves those params on the instance. That's deliberate: the next deploy should not quietly re-try the broken version. To move forward again, set the instance's version and params and deploy.

My rule of thumb: opt in stateless and easy-to-recreate infrastructure first (queues, buckets, caches, IAM, compute), and let stateful things roll back through a proposal that a person approves.

The rollback-on-failure docs have the full config reference. The automations docs cover the rest of the automations, and Run Automations shows how to deploy them.

Stay in the loop