absurdum reductus

Two Clean Applies That Rotated Nothing

We asked for a credential to be rotated. The gate held the change, we approved it, the apply ran green, the completion marker came back matching, and the gate closed again behind it. The store still held version 1. We shipped a fix and did the whole thing a second time. Green again, version 1 again, and not one error anywhere, either time.


A change that has to ask first#

Some of our infrastructure is declared as Crossplane resources whose real work is done by OpenTofu: a composite resource renders a Workspace, and provider-opentofu runs tofu init and tofu apply against it in a working directory inside its pod. For credentials we added a gate on top. A change to a credential’s spec does not apply on merge. It pends, and the resource publishes a short hash of the spec it is waiting on. Approving means writing that hash back into the spec in a second merge. The workspace then applies exactly once and closes again.

The part that matters here is how the gate knows the apply happened. The spec hash is passed into the module as a variable, and the module echoes it back as an output. Outputs only change when an apply runs, so when the echoed hash equals the requested one, the approved spec has been applied. That is the completion marker. It is a good mechanism, and it did exactly what it was built to do all day.

The first rotation drill was a counter in the spec, rotate, going from 0 to 1. The module was supposed to treat a change in that counter as the signal to replace the generated password and write version 2 to the store. We merged the bump, and the gate held it: no apply, the pending hash published. We merged the approval, and one apply ran. The echoed hash caught up. The gate closed. Every layer we could look at said the rotation was done.

The version number had not moved.

Green, and still version one#

The first suspects were all forms of lag. Perhaps the store had the new version and the status field on the resource had not caught up with it. Perhaps the write was still on its way to wherever we were reading from. Perhaps the module had the change and the cluster had not caught up with the module.

Reading more logs does not separate those. Every log line we had came from the component that had just told us it succeeded, and it was not going to start disagreeing with itself.

A witness the write path does not own#

So we asked something else. The same system can declare a read-only view of a credential family: a second resource, with its own database connection, that reads the store through a replica and reports what it finds. It shares nothing with the write path except the name of the thing being looked at. We declared one for the family we had just rotated and waited for it to reconcile.

It said version 1, and it was still saying it more than an hour later. The status field was in fact stale too — that turned out to be a separate problem, and we come back to it below — but it was not the reason for the missing version. No new version had been written. Two of the three suspects went in one read, and the question became narrow: why did an apply that ran do nothing?

The answer was in the module. The commit that taught it to replace the password when rotate changed had merged upstream a little over two hours before the workspace first ran tofu init. The in-cluster mirror the pod clones from refreshes every eight hours, and it picked the commit up more than three hours after that init. So the very first clone was of a module that had never heard of rotate.

And the module did not object. It took its settings as an untyped object and read each key with try(), so an unknown key was simply ignored. No warning, no error, a clean plan with nothing to do. From outside, that is indistinguishable from a rotation.

The fix that was right and never ran#

The module was sourced at ?ref=master, a floating reference, and the mirror had long since caught up. The obvious diagnosis was that tofu init does not refresh a module it has already installed. That is correct, and the OpenTofu documentation says it in as many words: re-running init installs modules added since the last init, “but will not change any already-installed modules. Use -upgrade to override this behavior.”

The provider has a field for extra init arguments, so the fix was one line, initArgs: ["-upgrade"]. We shipped it with a second rotation riding along, the counter at 2 and the approval for exactly that spec already in place.

The apply ran green. The marker came back. The gate closed. The witness read version 1, and so did a direct query of the store.

Somebody else’s early return#

At that point the only honest move was to read the controller. This is provider-opentofu v1.1.4, from the function that connects to a workspace at the start of every reconcile (an excerpt, unedited but for one level of indentation):

if cr.Status.AtProvider.Checksum != "" {
	checksum, err := tofu.GenerateChecksum(ctx)
	if err != nil {
		return nil, errors.Wrap(err, errChecksum)
	}
	if cr.Status.AtProvider.Checksum == checksum {
		l.Debug("Checksums match - skip running tofu init")
		return &external{tofu: tofu, kube: c.kube, logger: c.logger}, errors.Wrap(tofu.Workspace(ctx, meta.GetExternalName(cr)), errWorkspace)
	}
	l.Debug("Checksums don't match so run tofu init:", "old", cr.Status.AtProvider.Checksum, "new", checksum)
}

o := make([]opentofu.InitOption, 0, len(cr.Spec.ForProvider.InitArgs))

Three facts fall out of it and the code around it.

And one more from elsewhere in the same file: the workspace’s variables reach tofu as -var arguments on the command line. They are not written to a file. Our rotation counter and our approval hash were variables. Changing them changed nothing in the working directory.

Put those together and the floating reference cannot float. The cached module keeps the checksum stable. The stable checksum skips init. Skipping init preserves the cached module. Nothing in that loop ever looks at the upstream branch, and the one setting we added to make it look sits on the path the loop never takes. provider-terraform, the Terraform counterpart, has the same check at v1.2.0.

A cache that keeps itself#

That is a claim about code, so we built the smallest thing that would show it: a module in a local git repository, a working directory that sources it at ?ref=master, and a shell function that follows the controller’s rule, using its checksum command verbatim. terraform_data stands in for the password so nothing needs downloading.

#!/bin/sh
# A module in a git repo, a workdir that sources it at ?ref=master, and the
# controller's rule: skip init when the workdir checksum matches the last one.
set -e
R=$PWD
g() { git -C "$R/mod" -c user.name=rig -c user.email=rig@example.com "$@"; }

mkdir mod && git -C mod init -q -b master
cat > mod/main.tf <<'EOF'
variable "config" { type = any }
resource "terraform_data" "credential" {
  input = "minted"
}
output "id" { value = terraform_data.credential.id }
EOF
g add . && g commit -qm "v1: no rotation"

mkdir work && cat > work/main.tf <<EOF
terraform {
  backend "local" { path = "../state/state.json" }
}
variable "config"    { type = map(number) }
variable "spec_hash" { type = string }
module "family" {
  source = "git::file://$R/mod?ref=master"
  config = var.config
}
output "applied_spec_hash" { value = var.spec_hash }
output "credential"        { value = module.family.id }
EOF

sum() {   # the controller's checksum command, verbatim
  (cd work && /usr/bin/find . -path ./.git -prune -o -path ./.opentofu/providers \
    -prune -o -type f -exec /usr/bin/md5sum {} + | LC_ALL=C /usr/bin/sort \
    | /usr/bin/md5sum | /usr/bin/awk '{print $1}')
}
last=""
reconcile() {   # $1 = the rotate counter; the rest are initArgs
  n=$1; shift
  if [ -n "$last" ] && [ "$(sum)" = "$last" ]; then
    echo "   checksums match - skip init"
  else
    echo "   init $*" && (cd work && tofu init -input=false -no-color "$@" >/dev/null)
  fi
  (cd work && tofu apply -auto-approve -input=false -no-color \
    -var "config={rotate=$n}" -var "spec_hash=spec-$n" >/dev/null)
  last=$(sum)
  echo "   applied_spec_hash=$(cd work && tofu output -raw applied_spec_hash)" \
       "credential=$(cd work && tofu output -raw credential | cut -c1-8)"
}

echo "1. first reconcile, module v1"
reconcile 0

sed -i 's/  input = "minted"/  input = "minted"\n  triggers_replace = try(var.config.rotate, 0)/' mod/main.tf
g commit -qam "v2: rotate keeper"
echo "2. v2 merged to master; rotate=1"
reconcile 1

echo "3. add initArgs -upgrade; rotate=2"
reconcile 2 -upgrade

sed -i "s|?ref=master|?ref=$(g rev-parse HEAD)|" work/main.tf
echo "4. pin the ref to v2's commit; rotate=3"
reconcile 3 -upgrade

Run with OpenTofu 1.8.5 (the identifiers are random, so yours will differ):

1. first reconcile, module v1
   init 
   applied_spec_hash=spec-0 credential=177b3a05
2. v2 merged to master; rotate=1
   checksums match - skip init
   applied_spec_hash=spec-1 credential=177b3a05
3. add initArgs -upgrade; rotate=2
   checksums match - skip init
   applied_spec_hash=spec-2 credential=177b3a05
4. pin the ref to v2's commit; rotate=3
   init -upgrade
   applied_spec_hash=spec-3 credential=707b075e

Steps 2 and 3 are our two drills. The marker tracks the request perfectly, spec-1, spec-2, and the credential does not change. Only step 4, which edits a file the checksum can see, gets init to run and the keeper to fire.

We ran two controls beside it, because a rig that can only agree with you proves nothing. With the checksum rule removed, so that init runs every time, a plain init at step 2 still leaves the old module in place, and step 3’s -upgrade rotates: the one-line fix was right, just unreachable. And with -upgrade taken off step 4, the pin bump rotates anyway, because a changed source address makes even a plain init reinstall the module.

The pin is the invalidation#

The fix that worked is the oldest convention there is. Pin the module to a commit and deliver changes by bumping the pin, like any other dependency. The bump edits the module source in the rendered configuration, which changes the checksum, which runs init, which fetches the new code. The mechanism that froze the floating reference is the same one that makes a pinned reference reliable: the cache invalidates when, and only when, the text that names the code changes.

We kept -upgrade in initArgs anyway. It costs nothing when init is skipped, and it says what we mean when init runs.

The third drill carried the pin. One apply, the marker came back, the gate closed — the same three signals as the two drills before it, which is the point. This time the witness read version 2, and so did the direct query. Then we went looking for every other floating module reference in our compositions and pinned those too.

The same property, pointing the other way#

The stale status field was real, and it is the same mechanism seen from the other side. Outputs change only on apply, which is what makes the echoed hash a trustworthy record of the last apply. A gated workspace almost never applies, by design. So anything else projected from its outputs — here, the credential’s current version — is a snapshot of the last apply, and between applies it stops tracking the store altogether.

The status of a gated resource therefore looked live and was a snapshot. We fixed it by composing a second, always-on read-only workspace into the same resource, the same kind of witness that had answered our question, and taking the live fields from it. The gated workspace still owns the lifecycle fields, the ones that are supposed to mean “last applied”.

What a marker can testify to#

Every signal that went green that day was true. The gate held, the apply ran, the echoed hash matched, the gate closed. None of them was evidence of a rotation, because each was produced by the component we were asking about, describing its own run. An echoed completion marker testifies that an apply happened. It cannot testify that the apply did anything, and the cases where it did nothing are exactly the ones where you need it to.

So the rule we work to now is about the channel, not the tool. A change whose purpose is an effect somewhere else — a new credential version, a replaced certificate, a row that should exist — is verified by reading that somewhere else, through something the changed component does not own. Before the change, write down what the reader should say afterwards. If you cannot name such a reader, the change is not finished being designed.

The reader cost us one small resource declaration. Not having it cost us two clean applies, more than four hours, and a fix that was correct and could never run.