Open table of contents
What Nix restores, and what the cluster retains
NixOS can declare a Kubernetes node’s kernel, containerd, Kubernetes binaries, systemd units, network configuration and monitoring agents together. Locking a flake’s input graph also records which sources were selected before and after an update. [1]
But nixos-rebuild switch --rollback does not restore a Kubernetes cluster to an earlier state. Data written to etcd or local disks, CRD conversions, databases on persistent volumes and rotated credentials survive a host-generation change.
Separate the host configuration reproduced by Nix from persistent state recovered through other procedures. Version pinning is one part of that design. The intermediate states, rollout sequence, stop conditions and recovery evidence matter just as much.
The sample bundle contains a package-pinning flake, module fragments, declared-version skew checks, selected read-only preflight checks, a snapshot example and runbooks. It is not a complete NixOS cluster configuration. Sample lock generation, Nix evaluation/builds, validation scripts, cluster reads, snapshots, drains, activation, reboots and restores were not executed for this article. The examples describe intended procedures, not successful execution evidence.
1. Separate four recovery responsibilities
Scroll horizontally to view the complete diagram.
Read the diagram as text
Git and locks reproduce host closures. etcd snapshots recover API state; database and storage backups recover application data; PKI and secret procedures recover trust. Associate these recovery points. Switching a host generation does not rewind the other states.
| Recovery target | Main mechanism | What it does not restore |
|---|---|---|
| Host | Retained NixOS closure and host configuration | Mutable /var, etcd, external services and firmware |
| Kubernetes API state | Compatible etcd snapshot and reconstruction; GitOps reconciliation | PV contents and external controller side effects |
| Application data | Database-native backups/logs and storage snapshots | Cluster configuration and identity |
| Trust | PKI, secrets, identity and encryption-key recovery or rotation | Selecting an old generation alone does not re-establish trust |
etcd holds the main persistent Kubernetes API state, including Deployments, Secrets, CRDs and custom resources. It does not hold the contents of persistent volumes or every external API service. GitOps also leaves generated resources and dynamic state that were never committed to Git. [2]
A recovery point associates a Git revision, host closures, an etcd snapshot, application data and access to the required keys. Nearby timestamps alone do not prove that these artifacts are consistent.
2. Pin inputs and inspect the resulting package
A branch such as nixos-26.05 moves. flake.lock records resolved input revisions and hashes. The example also states immutable commits explicitly and separates the host input from the Kubernetes package input. [1]
{
description = "Kubernetes package provenance and host module fragments (not a cluster deployment)";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/4cd9ab252937ca5a5b39a3af8e66b9c39e336baa";
nixpkgs-k8s.url = "github:NixOS/nixpkgs/ed67a1e3aaaa0a03b7e8a3dcf56dcab7ecc518fa";
};
outputs = { self, nixpkgs, nixpkgs-k8s }:
let
system = "x86_64-linux";
hostPkgs = import nixpkgs { inherit system; };
k8sPkgs = import nixpkgs-k8s { inherit system; };
versionSet = {
evidenceKind = "evaluated package definitions, not running-node inventory";
hostInputRevision = nixpkgs.rev;
kubernetesInputRevision = nixpkgs-k8s.rev;
kubernetes = k8sPkgs.kubernetes.version;
kubectl = k8sPkgs.kubectl.version;
containerd = hostPkgs.containerd.version;
kernel = hostPkgs.linuxPackages.kernel.version;
cniPlugins = hostPkgs.cni-plugins.version;
etcd = hostPkgs.etcd.version;
};
in {
lib.versionSet = versionSet;
packages.${system} = {
kubernetes = k8sPkgs.kubernetes;
kubectl = k8sPkgs.kubectl;
version-manifest = hostPkgs.writeText "version-set.json" (builtins.toJSON versionSet);
};
nixosModules.packagePin = import ./modules/package-pin.nix {
inherit k8sPkgs;
};
nixosModules.provenance = { ... }: {
environment.etc."infra-revision".text = self.rev or self.dirtyRev or "unknown";
};
};
}
This flake exports packages, version information and module fragments. It supplies no hardware configuration, firewall, PKI, HA membership, CNI network or nixosConfigurations. An adopting host repository must complete, evaluate and build the actual system.
The inspected package definitions contain the following versions. These are values observed in source, not results from building the binaries. [3]
| Input | Pinned revision | Kubernetes definition |
|---|---|---|
| Host / NixOS modules | 4cd9ab252937ca5a5b39a3af8e66b9c39e336baa | 1.36.3 |
| Kubernetes packages | ed67a1e3aaaa0a03b7e8a3dcf56dcab7ecc518fa | 1.37.0 |
Generate, review and commit the actual flake.lock in the adopting environment. The bundle does not invent unresolved lockfile hashes. A pinned revision does not prove source or binary-cache availability, cache trust or a successful build.
Separate inputs do not establish dependency or ABI compatibility. Review whether the new binaries accept flags and configuration emitted by the host’s NixOS module revision. Dependencies from the Kubernetes input also enter its closure, so this is not proof that nothing except Kubernetes changes.
3. A common package is not a component rollout mechanism
The module fragment selects the package as follows.
# Import only into a separately reviewed NixOS host configuration.
# This common package changes ALL enabled native Kubernetes components on that host.
{ k8sPkgs }:
{ lib, ... }:
{
services.kubernetes.package = k8sPkgs.kubernetes;
assertions = [{
assertion = lib.versions.majorMinor k8sPkgs.kubernetes.version == "1.37";
message = "Review the intended Kubernetes minor before adopting this package set.";
}];
}
This does not resolve a package from a SemVer range. It selects the pinned input’s package and asserts the intended minor. Inspect the exact patch and built binaries separately.
In the referenced NixOS module, API server, kubelet, controller-manager, scheduler and proxy commands all use services.kubernetes.package. The master role also enables several co-located services and etcd. [3]
Changing the package on one control-plane host can therefore change more than its API server. A host-at-a-time switch is not automatically an API-server-at-a-time upgrade.
Do not treat the common package as a generic HA minor-upgrade procedure
Suppose API servers temporarily run 1.37 / 1.36 / 1.36. If the first host’s kubelet or controller can reach a 1.36 API through the common load balancer, that consumer cannot yet move to 1.37. [4]
First establish a rollout mechanism appropriate to the deployment: dedicated API hosts, separately controlled component units/packages, or a suitable lifecycle tool. The sample does not implement that orchestrator. It includes an example plan that should reject an update which overlooks this package coupling.
Kubeadm static-Pod management and upgrade phases do not automatically manage native NixOS systemd services. Use its guidance for sequencing and review topics while keeping ownership of binaries, manifests, certificates and etcd explicit. [5]
4. Check every API a component can reach
This example checks an upgrade from Kubernetes 1.36 to 1.37 against the official version-skew policy. The following summarizes the recent versions covered by this example. Older versions and particular distributions can impose additional constraints. [4]
| Component | Constraint to inspect |
|---|---|
| HA API servers | At most one minor between newest and oldest |
| kubelet | No newer than a reachable API; at most three minors older |
| kube-proxy | No newer than a reachable API; at most three minors older; also check its skew with the local kubelet |
| Controller / scheduler / cloud-controller | No newer than a reachable API; normally the same minor, with one minor older allowed during transition |
| kubectl | Within one minor, older or newer, of each reachable API |
Mixed HA versions narrow the permitted range. Checking only kubelet <= min(API) misses whether the kubelet is too old for the newest API. Inventory load-balancer destinations and failover routes as well as the ordinary path.
Scroll horizontally to view the complete diagram.
Read the diagram as text
With APIs at 1.37, 1.36 and 1.36, consumers using the common load balancer can reach an older API. A 1.37 kubelet or controller is not supported on that path. A common NixOS package can change several services together, so rollout needs component-level sequencing.
Do not skip an API-server minor. Review the current minor’s latest patch before moving to the next minor’s latest patch. The sample plan’s 1.36.3 is an illustrative source baseline, not clearance to bypass patch preparation. [4][5]
Supported skew describes coexistence; it does not authorize a downgrade. Whether an older binary can read changed data or stored API representations is a separate question.
5. Record built artifacts separately from running processes
The inspection example reads package definitions and binary versions.
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
test -f flake.lock
# Requires a reviewed lockfile; never update inputs during this inspection.
nix eval --no-update-lock-file --json .#lib.versionSet
package_path="$(nix build --no-update-lock-file --no-link --print-out-paths .#kubernetes)"
for component in kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy; do
"${package_path}/bin/${component}" --version
done
# kubectl is linked from a separate package; do not infer its version from kubernetes.version.
"${package_path}/bin/kubectl" version --client -o json
# This builds/executes package binaries. It does not evaluate a host toplevel, switch, or query a cluster.
The referenced Kubernetes package links kubectl from a separate package. Do not infer every executable’s version from kubernetes.version. Likewise, distinguish a package set’s kernel/containerd attributes from the actual selections in the final host configuration. [3]
Review Kubernetes, containerd, etcd, CNI binaries, CNI controller/DaemonSet images, CSI, kernel, cgroups, firewall, admission webhooks, operators and workload images together. Pinning nixpkgs does not automatically pin external charts or mutable image tags.
Declaring CNI packages is also different from deploying the network implementation.
# This declares an additional package; it does not install/configure a complete CNI system.
{ pkgs, ... }:
{
services.kubernetes.kubelet.cni.packages = [ pkgs.cni-plugins ];
}
# NixOS list definitions merge. Inspect the final evaluated list and module-provided defaults.
# Do not use mkForce to erase defaults without reviewing the selected CNI implementation.
NixOS module lists merge, including plugins added by defaults. This fragment does not necessarily replace the final list. The referenced module links binaries into /opt/cni/bin, and the kubelet runtime endpoint defaults to unix:///run/containerd/containerd.sock; runtime and CNI configuration and operating state still need to be established. [3]
A Git revision marker is not running-state evidence
nixosModules.provenance = { ... }: {
environment.etc."infra-revision".text = self.rev or self.dirtyRev or "unknown";
};
The marker identifies configuration provenance. Do not treat dirty or unknown revisions as approved production artifacts. During an incident, correlate it with additional evidence:
cat /etc/infra-revision
readlink -f /run/current-system
readlink -f /run/booted-system
uname -r
systemctl show kubelet --property=MainPID --property=ExecStart
After switch, the running kernel may remain old until reboot. Keep the marker, profile, booted closure, process binary and Kubernetes-reported version distinct. A Git revision alone does not prove that every node finished activation.
6. Inspect each intermediate state in the declared plan
The bundled rolling-plan.json declares API-server changes first, then controllers, drained nodes and operator tooling. Each component lists the API IDs it can reach. The central state check is:
def check_state(state):
apis = {key: version(item["version"])[1] for key, item in state.items()
if item["kind"] == "kube-apiserver"}
require(bool(apis), "No API server inventory")
require(max(apis.values()) - min(apis.values()) <= 1, "HA API skew exceeds one minor")
for key, item in state.items():
current = version(item["version"])[1]
kind = item["kind"]
if kind == "kube-apiserver":
continue
peers = item.get("api_servers", [])
require(bool(peers) and len(peers) == len(set(peers)), key + ": missing/duplicate API peers")
require(all(peer in apis for peer in peers), key + ": unknown API peer")
reached = [apis[peer] for peer in peers]
if kind in ("kubelet", "kube-proxy"):
require(all(0 <= api - current <= 3 for api in reached), key + ": node/API skew")
if kind == "kube-proxy":
paired = state.get(item.get("kubelet_id"), {})
require(paired.get("kind") == "kubelet", key + ": missing paired kubelet")
require(abs(current - version(paired["version"])[1]) <= 3, key + ": proxy/kubelet skew")
elif kind in ("kube-controller-manager", "kube-scheduler", "cloud-controller-manager"):
require(all(0 <= api - current <= 1 for api in reached), key + ": controller/API skew")
elif kind == "kubectl":
require(all(abs(api - current) <= 1 for api in reached), key + ": kubectl/API skew")
else:
raise ValueError(key + ": unsupported component kind " + kind)
python3 scripts/validate-skew.py review/rolling-plan.json
python3 scripts/validate-skew.py review/rejected-coupled-switch.json
The expected outcomes are that the first plan meets the implemented rules and the second fails because it advances consumers on the first control-plane host too early. These commands were not run for this article. The validator also conservatively rejects downgrades and skipped minors.
It checks supplied declarations only. It cannot discover an omitted cloud-controller or an inaccurate peer list, and it does not inspect service restart order inside a single step. Compare the plan with running-version inventory and verify the actual activation transients as well.
7. Make preflight conditions stronger than command success
kubectl get pods can exit successfully while displaying unhealthy Pods. A Pod can also be Running while containers are unready or crash-looping. Printing that output and then unconditionally announcing “Preflight passed” is insufficient.
The sample preflight checks each explicit API’s /readyz and /version, expected node inventory and readiness, unready/terminating Pods, and selected etcd endpoint health, status and alarms. It stores scoped evidence. Its Pod check is:
record["unready_pods"] = []
for pod in pods:
status = pod.get("status", {})
if status.get("phase") == "Succeeded":
continue
ready = any(c["type"] == "Ready" and c["status"] == "True" for c in status.get("conditions", []))
if status.get("phase") != "Running" or not ready or pod["metadata"].get("deletionTimestamp"):
record["unready_pods"].append({"namespace": pod["metadata"]["namespace"],
"name": pod["metadata"]["name"], "phase": status.get("phase"), "ready": ready})
require(not record["unready_pods"], "Unready/terminating pods; review the baseline, do not silently ignore")
A successful readyz through one load balancer does not establish every API instance’s health. Supply correct TLS names and authority for direct endpoints. For etcd, also check that the endpoints identify distinct members of the same cluster.
Successful read checks do not establish PDB feasibility, scheduling capacity, CNI/CSI behavior, webhook compatibility, removed API use, CRD conversion or workload SLOs. Review existing unready resources and any explicit baseline exceptions rather than silently ignoring failures the script cannot explain.
8. Associate snapshots with a restoration procedure
With etcd 3.6, use etcdctl snapshot save for collection and etcdutl for inspection and restoration. Copying a database file directly from a live data directory can omit changes still in its WAL. [6]
etcdctl --endpoints="$SNAPSHOT_ENDPOINT" \
--cacert="$ETCD_CA" --cert="$ETCD_CERT" --key="$ETCD_KEY" \
snapshot save "$output_dir/snapshot.db"
etcdutl snapshot status "$output_dir/snapshot.db" --write-out=json > "$output_dir/status.json"
The example script writes a new directory and records snapshot status, file SHA-256, observed cluster/version identifiers, Git revision and host closure. It distinguishes etcd’s status hash from the whole-file SHA-256. Local artifact creation does not claim successful remote storage or restoration.
"local_status": "snapshot_saved_and_inspected", "remote_copy_verified": False,
"isolated_restore_verified": False,
Snapshots contain sensitive API data. Plan encrypted staging storage, restricted access, transfer to a separate recovery domain, retrieval of the external copy and hash verification. For S3 retention and authority separation, see the Object Lock recovery design. [2]
If Kubernetes encryption at rest is enabled, recovery also needs the relevant encryption keys or KMS access. Putting PKI client keys into the Nix Store is not a substitute for independent secret management and recovery paths. [7]
Readable snapshot status does not establish that the restored API can decrypt Secrets, read CRDs or run controllers correctly. Associate the upgrade gate with a compatible isolated restore exercise and corresponding recovery artifacts.
9. Sequence APIs, consumers and nodes
Scroll horizontally to view the complete diagram.
Read the diagram as text
Begin with compatibility review, builds, verified external snapshots and an associated restore drill. Update APIs individually, then controllers when all reachable APIs permit it. Drain, activate, reboot if needed, verify workloads and uncordon each node. Stop on failure at any gate and preserve etcd quorum throughout.
Advance API servers individually, then update controllers and schedulers once their reachable APIs permit it. Drain each node before a kubelet minor change, including control-plane hosts that run kubelet. Preserve etcd quorum independently; API replica count alone is not enough. [4]
A drain can begin with:
kubectl --context "$REVIEWED_CONTEXT" drain "$REVIEWED_NODE" \
--ignore-daemonsets --timeout=15m
--ignore-daemonsets does not evict DaemonSet Pods. Treat PDB rejection, insufficient rescheduling capacity and undecided emptyDir or local-volume handling as stop conditions. Do not put --force, --disable-eviction or --delete-emptydir-data into the routine defaults. [8]
Apply the reviewed host closure and reboot if required. Before uncordoning, inspect DNS, Pod networking, CSI mounts, a representative workload, metrics, logs and alerts as well as NodeReady. Observe workload recovery before advancing to the next node.
Patch updates still need release-note and state/runtime review. They may require less investigation than a minor upgrade, but a patch label does not imply reversible or disruption-free behavior. Deliberately choose whether NixOS, runtime, CNI and Kubernetes move separately or together based on compatibility and diagnosis needs.
10. Inspect what an old host generation would revert
A retained previous generation can help recover a broken kernel boot or unit configuration. But if it also contains older Kubernetes or containerd binaries, those may revert too. Mutable /var/lib/containerd, etcd, certificates and service-driven migrations are not automatically reversed. [9]
This article therefore does not offer “return API server 1.37 to 1.36” as a general recovery recipe. Inspect state, flags, runtime data formats, reachable versions and the distribution’s recovery procedure. A fix-forward or node replacement may be more appropriate. Supported skew is not downgrade permission.
Temporary activation with NixOS test also does not undo service writes. Distinguish selecting an earlier generation at boot from activating a running system. Deleting old GC roots or closures can remove the immediate recovery path. Git may survive while the sources or caches needed for a rebuild are unavailable. [9]
11. Restore etcd as a new logical cluster
One lost member with healthy quorum differs from irrecoverable quorum or state loss. Do not jump from the former to restoring the entire cluster. Nor is snapshot recovery a way to mix one member restored to an old point with the still-running original membership. [6]
Scroll horizontally to view the complete diagram.
Read the diagram as text
Stop every API and fence old members and writers. Restore the same verified snapshot into new per-member directories with common membership and distinct peers. Use a justified revision bump and compaction to invalidate old watches. Verify decryption, resources and controllers through compatible APIs, then reconcile PV and external state.
Kubernetes guidance stops all API servers before restoring etcd and resumes them afterward. Restoring the same snapshot reconstructs member and cluster identities into a new logical cluster. Verify compatible etcd major/minor versions for the snapshot and restore tools. [2][6]
The following is a per-member template for an approved isolated environment. The bundle does not include a script that overwrites a running data directory.
etcdutl snapshot restore "$VERIFIED_SNAPSHOT" \
--name "$NEW_MEMBER_NAME" \
--data-dir "$NEW_EMPTY_DATA_DIR" \
--initial-cluster "$NEW_CLUSTER_MEMBERSHIP" \
--initial-cluster-token "$NEW_CLUSTER_TOKEN" \
--initial-advertise-peer-urls "$NEW_MEMBER_PEER_URL" \
--bump-revision "$REVIEWED_REVISION_BUMP" \
--mark-compacted
Each member needs a unique name, new data directory and peer URL. All use the same snapshot, new membership definition and token. Match runtime configuration, client/peer TLS, ownership and volumes. Do not delete the old directory just to make a restore command succeed.
Justify the revision bump
Restoring an older revision can leave Kubernetes informers and watch consumers holding knowledge from a later state. etcd guidance strongly recommends --bump-revision and --mark-compacted for Kubernetes recovery. [6]
Choose a bump exceeding the revision interval consumers could have observed since the snapshot, using snapshot age, an upper bound on write rate and margin. The documentation’s billion-revision example is not a universal constant. After invalidating watches, restart or reconcile the necessary consumers and inspect new LIST/watch behavior.
During drills, isolate restored controllers from production cloud resources, databases and other side effects. During an actual incident, reconcile older API objects with newer PV data, changes lost since the snapshot and workloads that continued running while the control plane was unavailable. Restoring etcd does not rewind an application database.
12. Keep PKI and stateVersion separate from package selection
Embedding a secret in environment.etc.<name>.text can put it into the Nix Store. Declare paths, ownership, permissions and delivery mechanisms in configuration, and supply the values through the environment’s secret-management system, such as sops-nix, agenix or systemd credentials. Selecting a mechanism does not by itself resolve key loss or compromise. [10]
When reverting a host after certificate rotation, distinguish re-trusting a revoked identity from safely retaining old encryption-key versions needed for decryption. Recovery from compromise requires more than retrieving an earlier secret.
system.stateVersion preserves compatibility with stateful defaults associated with the initial installation. It neither selects the package source nor declares the current Kubernetes version. Do not raise it simply because Kubernetes changes. The referenced module advises generally retaining the original value after installation. [11]
13. Use pinning to support a continuing update process
Do not declare success solely from node version strings.
| Layer | Evidence for completion |
|---|---|
| Host | Approved closure, booted kernel, running binaries, network and runtime |
| Kubernetes | Supported skew across components and reachable APIs; API, etcd and controller function |
| Workloads | Scheduling, networking, storage, representative transactions and SLOs |
| Observability | Continued metrics, logs, traces and alerts; correlation with the change time |
| Recovery | Externally stored and retrievable artifacts, decryption keys and a compatible restore drill |
Compare longer trends before and after the update, and observe logs and telemetry collection paths during it. Record infrastructure revisions as metadata or change events without attaching unbounded revision labels to every request metric.
Retain old closures and snapshots long enough for delayed regressions and the recovery policy. Inventory, runbooks and notification paths must remain accessible when the cluster is unavailable.
Pinning supports deliberate updates. Track maintenance windows and security fixes, then move through input review, builds, compatibility checks, snapshots, staged activation and observation. A lockfile change and green CI are not automatically production deployment approval.
The related observability modernization case provides attributed design context. It does not establish that the NixOS configuration, Kubernetes versions, upgrades or snapshot/restore exercises in this article were delivered or measured in that engagement.
Use Nix to reproduce the target host, Kubernetes policy to constrain the transition, state-specific backups to establish recovery points, and observability to assess the result. Making the scope of “rollback” precise is the starting point for declarative Kubernetes operations.
From VLANs to enforcement develops the implementation with a NixOS/nftables policy catalog and configuration examples. It connects gateway paths, IPv4/IPv6, connection state, denial evidence and service lifecycle behavior.
References
- Nix Flakes — Input graphs and locking.
- Kubernetes: Operating etcd — Backups, compatibility and stopping APIs for restoration.
- Pinned NixOS Kubernetes module — Common package and roles; API server, kubelet, controller, scheduler, proxy, host package, target package and kubectl.
- Kubernetes Version Skew Policy — Maintained branches, mixed HA versions and component constraints.
- Upgrading kubeadm clusters — Patch preparation and sequencing; not a native-systemd execution procedure.
- etcd 3.6 Disaster Recovery — Snapshots, membership, revision bump and compaction; also upgrade to 3.6.
- Kubernetes Encryption at Rest — Key retention and decryption dependencies.
- Safely Drain a Node — Eviction, PDBs, DaemonSets and local data.
- NixOS Manual — Generation switching, boot, garbage collection and closure retention.
- NixOS Manual: Secret handling — Keeping secrets out of the Nix Store; see service-specific secret-file guidance.
- Pinned system.stateVersion definition — Compatibility value associated with the initial installation.
NixOS modules/packages use the pinned revisions above, and etcd guidance targets 3.6. Source values, declared plans and expected outcomes are distinct from built, running or restored evidence.