Flux¶
Flux CD is the GitOps engine for every cluster: it watches this repository and continuously reconciles cluster state to match it. Flux is unusual among the components here because it manages itself — once bootstrapped, changes to its own HelmRelease are applied by the very controllers that release updates.
Overview¶
Dependencies¶
Flux has no dependency on other GitOps-managed components — it must come up before anything else can be reconciled. Its only prerequisite is a working CNI (Cilium), which Terraform installs directly via the Helm provider before Flux exists, for exactly this reason.
Exposed Services¶
Flux has no externally routed service. It runs the source, kustomize, helm, notification, image-reflector, and image-automation controllers in the flux-system namespace.
Repository Layout¶
components/flux/
├── base/
│ ├── namespace.yaml # flux-system namespace
│ ├── helmrepository.yaml # fluxcd-community chart repo
│ ├── helmrelease.yaml # flux2 chart: enables all six controllers
│ └── kustomization.yaml
└── gitea-overlay/
├── gitrepository.yaml # GitRepository pointing at this repo's Gitea mirror
├── external-secret.yaml # Deploy key for the Gitea GitRepository, from OpenBao
├── configmap-patch-job.yaml # configmap-patcher RBAC and the Job that switches the Git source to Gitea
├── cron-job.yaml # Suspended templates: git-source-fallback, git-source-restore
├── switch-git-source.py # The guarded switch, shipped as ConfigMap git-source-switch
├── test_switch_git_source.py # Its tests against a fake Kubernetes and GitHub API
└── kustomization.yaml
└── taskbase-alerts/
├── provider.yaml # generic-hmac Provider "taskbase" (address set per cluster)
├── external-secret.yaml # Provider's HMAC key, from OpenBao (path set per cluster)
└── kustomization.yaml
Bootstrap: GitHub first, then Gitea¶
A new cluster can't clone from gitea.prod.skatzi.com before Gitea itself has been deployed by that same cluster — so Flux bootstraps in two stages on hetzner-mgmt, the cluster that hosts Gitea:
terraform/environments/hetzner-mgmt-cluster/2-components/main.tfinstalls theflux2Helm chart directly and creates an initialGitRepository(bootstrap-cluster, seecluster/hetzner-mgmt/flux/config/gitrepository.yaml) pointing at this repository on GitHub, authenticated via agithub-authsecret. Thecluster-configConfigMap'sgit_source_repositorykey starts out pointing at this GitRepository.- Once
openbaoandgiteaare deployed and healthy, theflux-system-gitea-overlayKustomization (components/flux/gitea-overlay) applies: it creates agitea-platformGitRepositorypointing atssh://git@gitea.prod.skatzi.com/Skatzi/platform.git(deploy key synced from OpenBao viaExternalSecret), then runs theswitch-to-gitea-sourceJob, which runsswitch-git-source.py gitea-platform: oncegitea-platformis Ready it patches thecluster-configConfigMap and thehetzner-mgmt-clusterKustomization'ssourceRefto point atgitea-platforminstead. Flux recreates the Job after its 5-minute TTL; on later runs it finds the source already switched and does nothing, or finds the fallback hold and leaves the source alone. From that point on, every Kustomization that uses${git_source_repository}reconciles from the in-cluster Gitea instead of GitHub.
Fallback source: Gitea push mirror to GitHub¶
After the switch, Flux on hetzner-mgmt pulls from the Gitea it also upgrades, so a Gitea upgrade that breaks Gitea would leave no Git source for a revert (decision #1161). To keep the GitHub bootstrap-cluster repository usable as a fallback, Gitea push-mirrors Skatzi/platform to it on every commit. Switching Flux to that fallback is covered in Switching to the fallback and back; this section covers keeping the copy current.
- What: a push mirror on
Skatzi/platformtohttps://github.com/${github_owner}/${github_repository}.git(DunkRing/bootstrap-cluster, the samecluster-configvalues thebootstrap-clusterGitRepository uses), with sync on commit and an 8-hour periodic push as a safety net. - Branch and history: Gitea pushes every branch and tag with
--mirrorand force (+refs/heads/*,+refs/tags/*;services/mirror/mirror_push.goin Gitea 1.25.5). GitHub's${github_branch}(main) therefore always equals Gitea'smain: a force-push or extra commits on GitHub are overwritten, and branches that exist only on GitHub are deleted. Never commit to the GitHub repository directly. A branch protection rule or ruleset on GitHub that forbids force pushes or deletions would block the mirror, so the bootstrap repository must not have one. - Declared as code:
components/gitea/push-mirror/, wired by thegitea-push-mirrorFlux Kustomization incluster/hetzner-mgmt/gitea/kustomization.yaml(dependsOn: [gitea]). The CronJobgitea/github-push-mirrorrunsreconcile-push-mirror.pyevery 15 minutes against the Gitea API with a Gitea access token (see Tokens); the push mirror API needs admin rights on the repository. It does not use the admin password (gitea-admin-secret): basic auth with it was refused with401on 2026-10-20 (#1375). It leaves a healthy mirror alone; when the mirror is missing, does not sync on commit, or its last push failed, it deletes it, creates it again with the current token and triggers a push. Gitea pushes before the sync call returns, so the run then reads the new mirror: when that push worked too, the run ends Complete, so a single transient GitHub error does not leave a failed Job (#2649); when it failed (an expired GitHub token, a branch protection rule), the run exits non-zero, so the Job shows as failed. When Gitea cannot be reached (refused, orOperation not permittedfrom Cilium for a Service with no endpoints), the first API call retries every 5 seconds for up to 14 minutes (840 s,GITEA_WAIT_SECONDS), so a run during a planned stop, such as the backup gate or a rollback scaling Gitea to 0, ends Complete once Gitea is back instead of leaving a failed Job (#1590). With Gitea up but its database down, Gitea answers401even to a valid token (#2500). So a401,500,502or503on that first call is retried the same way while Gitea's unauthenticated/api/healthzdoes not answer200withstatus: pass. A longer outage still fails the run. Any other HTTP error, or one from a healthy Gitea such as a wrong token, fails the run at once. Push mirrors to other addresses are left alone. Gitea keeps push mirrors in its database, so this also restores the mirror after a Gitea database restore. To run it now:kubectl --context admin@mgmt-cluster -n gitea create job --from=cronjob/github-push-mirror github-push-mirror-manual. - Tokens: both live in OpenBao at
clusters/hetzner-mgmt/gitea/github-mirror, and thegithub-mirror-tokenExternalSecretin thegiteanamespace syncs them hourly into the Secret of the same name. Propertygithub-mirror-token(keytoken) is a fine-grained GitHub personal access token limited toDunkRing/bootstrap-clusterwith Contents: read and write, created by a person (#1166); Gitea sends it as the password with${github_owner}as the user name. If the repository ever gains.github/workflows/files, it also needs the Workflows permission, or GitHub rejects the push. Propertygitea-token(keygitea-token) is a Gitea access token with scopewrite:repositoryof an account with admin rights onSkatzi/platform, which the reconciler sends asAuthorization: token. The Gitea backup gate and restore drill send the same token in their smoke check, through thegitea-tokenExternalSecretingitea-scratch. Write one property withbao kv patchso the other is kept. - Expiry and rotation: the GitHub token of 2026-10-19 had no expiry, yet GitHub rejected it a day later (#1375), so do not rely on an expiry date;
GiteaPushMirrorFailingreports a rejected token. To rotate it, create the new token, write it to the same OpenBao key, then revoke the old one on GitHub. The next push with the revoked token fails, and the following CronJob run recreates the mirror with the new token. To switch at once, run the Job by hand after the secret has synced (kubectl --context admin@mgmt-cluster -n gitea get externalsecret github-mirror-token) and delete the mirror under the repository's Settings → Repository → Mirror settings first, or the healthy mirror is kept. - Alert:
GiteaPushMirrorFailingfires when the CronJob has not succeeded for 50 minutes, three failed runs in a row; see its runbook. - Check that it works: after the next merge to
main,git ls-remote https://gitea.prod.skatzi.com/Skatzi/platform.git refs/heads/mainandgit ls-remote https://github.com/DunkRing/bootstrap-cluster.git refs/heads/main(both need read access) print the same SHA.Settings → Repository → Mirror settingsin Gitea shows the last update and any error, andkubectl --context admin@mgmt-cluster -n gitea logs job/<latest github-push-mirror job>shows what the reconciler did.
Switching to the fallback and back¶
When a Gitea upgrade breaks Gitea, the Gitea rollback Job points Flux at bootstrap-cluster and, once Gitea is healthy again, back at gitea-platform. Both directions run components/flux/gitea-overlay/switch-git-source.py with the configmap-patcher Role. The rollback Job runs the script itself, with a binding to that Role. By hand, run it from two suspended CronJobs in flux-system that serve as Job templates:
| Template | Runs | Does |
|---|---|---|
git-source-fallback |
switch-git-source.py bootstrap-cluster |
switches to GitHub and sets the hold |
git-source-restore |
switch-git-source.py gitea-platform --release |
switches to Gitea and clears the hold |
kubectl --context admin@mgmt-cluster -n flux-system create job --from=cronjob/git-source-fallback git-source-fallback-$(date +%s)
kubectl --context admin@mgmt-cluster -n flux-system logs -f job/git-source-fallback-<stamp>
A switch sets cluster-config's git_source_repository, which every platform Kustomization substitutes into its sourceRef, and the sourceRef of the root hetzner-mgmt-cluster Kustomization (created by Terraform, so it does not substitute), then sets reconcile.fluxcd.io/requestedAt on every Kustomization in flux-system. The Job exits 0 when it switched or had nothing to do, and 1 when a guard refused; it never retries (backoffLimit: 0), so the caller decides.
Guards. Before switching, the script asks Flux to fetch the target source again (reconcile.fluxcd.io/requestedAt on the GitRepository) and waits up to 180 s for status.lastHandledReconcileAt to match, the same handshake flux --context admin@mgmt-cluster reconcile source git uses (Flux GitRepository docs). It refuses when:
- the target GitRepository is not
Readyafter that fetch; - (to GitHub only)
gitea-platformhas no fetched artifact, orbootstrap-cluster's commit is not the same as, or ahead of, the last commit Flux fetched fromgitea-platform.
The commits are the SHAs in each GitRepository's status.artifact.revision (main@sha1:<sha>). Flux keeps the last artifact while a source fails, so gitea-platform's artifact is the newest Gitea commit this cluster has seen, even with Gitea down. Equal SHAs are the normal case: the push mirror updates GitHub on every commit. When they differ, the script asks GitHub's compare API (GET /repos/{owner}/{repo}/compare/{gitea}...{github}, authenticated with the github-auth token) and accepts only identical or ahead. behind, diverged, or a Gitea commit GitHub does not have (404) mean the mirror is stale or rewritten, and the switch is refused, so a stale mirror cannot roll the cluster back to older manifests. Commit dates are not compared: they say nothing about ancestry.
Hold. Switching to GitHub also sets the annotation platform.skatzi.com/git-source-hold: <UTC time> on cluster-config, in the same patch as the source. While it is set, switch-git-source.py gitea-platform without --release (which is what the recreated switch-to-gitea-source Job runs) logs the hold and exits 0 without touching anything, so it cannot flip Flux back to a Gitea that is still broken. Only git-source-restore (--release) switches back and clears the hold. The way back checks only that gitea-platform is Ready: Gitea is the source of truth, and its push mirror overwrites GitHub as soon as it runs, so a fix pushed only to GitHub during an outage must also be merged in Gitea before the switch back.
Gotchas.
terraform applyofhetzner-mgmt-cluster/2-componentsrewritescluster-config: it resetsgit_source_repositorytobootstrap-clusterand drops the hold annotation. That is no different from before this switch existed; the nextswitch-to-gitea-sourcerun switches back to Gitea.- The templates and the Job need the
python:3.15.2-alpineimage from Docker Hub, not Harbor, so they still start when platform services are down. - To run the tests:
python3 -m unittest components/flux/gitea-overlay/test_switch_git_source.py.
By hand. A person with kubectl and the flux CLI who cannot run the Jobs does the same. So does the operational agent on the Mac mini with its break-glass kubeconfig; it also pushes fixes to the mirror while Gitea is down (Disaster recovery: Git when Gitea is down):
# 1. Fetch GitHub now and compare commits; the GitHub one must equal or be ahead of the Gitea one.
flux --context admin@mgmt-cluster reconcile source git bootstrap-cluster -n flux-system
kubectl --context admin@mgmt-cluster -n flux-system get gitrepository gitea-platform bootstrap-cluster \
-o 'custom-columns=NAME:.metadata.name,READY:.status.conditions[?(@.type=="Ready")].status,REVISION:.status.artifact.revision'
# if the SHAs differ: https://github.com/DunkRing/bootstrap-cluster/compare/<gitea-sha>...<github-sha> must say "ahead"
# 2. Switch to GitHub and set the hold, in one patch.
kubectl --context admin@mgmt-cluster -n flux-system patch configmap cluster-config --type merge -p \
"{\"metadata\":{\"annotations\":{\"platform.skatzi.com/git-source-hold\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}},\"data\":{\"git_source_repository\":\"bootstrap-cluster\"}}"
kubectl --context admin@mgmt-cluster -n flux-system patch kustomization hetzner-mgmt-cluster --type merge -p '{"spec":{"sourceRef":{"name":"bootstrap-cluster"}}}'
kubectl --context admin@mgmt-cluster -n flux-system annotate kustomizations --all reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
# 3. Back to Gitea once it is healthy: check gitea-platform is Ready, then clear the hold with the switch.
flux --context admin@mgmt-cluster reconcile source git gitea-platform -n flux-system
kubectl --context admin@mgmt-cluster -n flux-system patch configmap cluster-config --type merge -p \
'{"metadata":{"annotations":{"platform.skatzi.com/git-source-hold":null}},"data":{"git_source_repository":"gitea-platform"}}'
kubectl --context admin@mgmt-cluster -n flux-system patch kustomization hetzner-mgmt-cluster --type merge -p '{"spec":{"sourceRef":{"name":"gitea-platform"}}}'
kubectl --context admin@mgmt-cluster -n flux-system annotate kustomizations --all reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
Verify on the cluster. With Gitea healthy, a dry run of both directions is safe, because GitHub mirrors the same main:
kubectl --context admin@mgmt-cluster -n flux-system get cronjob git-source-fallback git-source-restore configmap git-source-switchshows all three.- Run
git-source-fallback(above). Its log ends withswitched Flux to bootstrap-cluster (hold set);kubectl --context admin@mgmt-cluster -n flux-system get configmap cluster-config -o yamlshowsgit_source_repository: bootstrap-clusterand the hold;flux --context admin@mgmt-cluster get kustomizationsshows the source revisionsmain@sha1:<sha>unchanged. - Wait for the next
switch-to-gitea-sourceJob (up to 15 minutes) or runkubectl --context admin@mgmt-cluster -n flux-system get jobs; its log says the hold is set, and the source stays on GitHub. - Run
git-source-restore. Its log ends withswitched Flux to gitea-platform (no hold), and the hold annotation is gone.
Cluster wiring¶
cluster/hetzner-mgmt/flux/kustomization.yaml defines four Flux Kustomizations in order: flux-system (installs the chart), flux-config (applies the bootstrap GitRepository, dependsOn: [flux-system]), flux-system-gitea-overlay (dependsOn: [openbao, gitea]), and flux-taskbase-alerts (see Failure alerts to Taskbase, dependsOn: [flux-system, external-secrets-config]).
cluster/webshop/flux/kustomization.yaml defines only flux-system, with source platform (the GitRepository Terraform created there), a health check on the flux2 HelmRelease, and memory requests patched to that cluster's peaks. It took over the flux2 release Terraform installed (chart 2.18.2) in #3461, so a chart bump in components/flux/base upgrades both clusters. webshop has no flux-config, no Gitea overlay and no Taskbase alerts.
Failure alerts to Taskbase¶
On hetzner-mgmt, the notification-controller reports every failed HelmRelease and Kustomization to Taskbase, which turns it into a task that follows up the dependency upgrade that caused it (Renovate architecture §7).
HelmRelease / Kustomization fails (error event)
└─▶ Alert taskbase-<repo> (eventSeverity: error, eventMetadata cluster + repository)
└─▶ Provider taskbase (generic-hmac, X-Signature: sha256=<hex>)
└─▶ POST https://taskbase.skatzi.com/api/webhooks/flux
└─▶ task for (cluster, kind, namespace, name, revision)
- Provider and key (
components/flux/taskbase-alerts/): thetaskbaseProvidersigns each event with thetokenkey of thetaskbase-flux-webhooksecret. AnExternalSecretsyncs that key from OpenBaohetzner-mgmt/taskbase/flux-webhook, propertysecret— the value Taskbase verifies with. The address and OpenBao path are patched incluster/hetzner-mgmt/flux/taskbase-alerts/kustomization.yaml. - One Alert per source repository (
cluster/hetzner-mgmt/flux/taskbase-alerts/alert.yaml): Taskbase needs therepositorythe failing object comes from, so each Alert setseventMetadatacluster(from${cluster_name}) andrepository.taskbase-platform(Skatzi/platform) covers the roothetzner-mgmt-clusterKustomization, every platform Kustomization, and the HelmReleases in each namespace that holds one, exceptflux-system/flux2;taskbase-platform-flux2coversflux2withexclusionList: ['context canceled'], because anexclusionListapplies to a whole Alert and ontaskbase-platformwould also mute a backup gate's canceled health check;taskbase-taskbase(Skatzi/taskbase),taskbase-emiliero(Skatzi/emiliero) andtaskbase-helloweekly(Emmalia/Helloweekly) cover those repositories' Kustomizations.botyard-controlhas no Alert, becauseDupondforge/botyard-controlis not linked to a Taskbase project. - Source label: Alerts select Kustomizations by the label
platform.skatzi.com/source-repository. A Kustomization that reconciles another repository sets it itself (e.g.taskbaseincluster/hetzner-mgmt/taskbase-prod/kustomization.yaml); a patch incluster/hetzner-mgmt/kustomization.yamllabels every other oneplatform.
When you add a workload repository, label its Kustomization and, if the repository is linked to a Taskbase project, add an Alert for it. When you add a HelmRelease in a new namespace, add that namespace to taskbase-platform's eventSources — a namespace not listed there is not reported. A HelmRelease in flux-system must be added by name: that namespace is listed release by release, since event sources cannot exclude flux2.
Until the HMAC key exists in OpenBao the ExternalSecret fails to sync and nothing is sent. To check that events arrive: kubectl --context admin@mgmt-cluster -n flux-system get providers,alerts lists them and their age (a v1 Alert has no Ready condition); kubectl --context admin@mgmt-cluster -n flux-system logs deploy/notification-controller | grep taskbase shows failed posts (a 422 means a missing cluster, repository or revision; 401 a wrong key or an event older than 15 minutes); and the first failure shows up as a new task in the project linked to the repository.
Safe Change Workflow¶
- Chart version bumps / enabling a controller: edit
components/flux/base/helmrelease.yaml. Terraform installs the sameflux2release, so once the new chart isdeployed, raise its pins to match in a follow-up pull request (the module default also covers webshop, which runs the same chart from Git):versionofhelm_release.flux2interraform/environments/hetzner-mgmt-cluster/2-components/main.tfand theflux_versiondefault interraform/modules/hetzner/talos-cluster/components/variables.tf. Otherwise aterraform applydowngrades Flux until helm-controller reconciles again. This is self-referential — the runningkustomize-controllerandhelm-controllerapply the change to themselves. Check the Flux release notes for CRD changes between versions. Theflux2chart renders its CRDs fromtemplates/, so Helm upgrades them with the release and also rolls them back with it;crds: CreateReplaceonly governs a chart'scrds/directory. Before a Flux minor, run the pre-flight: a version still in a CRD's livestatus.storedVersionsmust be in the target chart'sspec.versions(Flux 2.9 removednotification.toolkit.fluxcd.io/v1beta2andimage.toolkit.fluxcd.io/v1beta2). Chart 2.20.0 (Flux 2.10) makesv1the storage version ofAlertandProvider, a version the 2.19.x chart does not have: once it is applied, a Helm rollback or a Terraform apply of an older chart fails onstatus.storedVersions, so the upgrade rolls forward only. flux2values are per controller. The fluxcd-community chart has no top-levelcontrollers,resourcesorsecurityContext; Helm accepts such keys and ignores them. Set them undersourceController,kustomizeController,helmController,notificationController,imageReflectionControllerandimageAutomationController(helm show values flux2 --repo https://fluxcd-community.github.io/helm-charts --version <v>), and check withhelm templatethat they reach the Deployments. The requests incomponents/flux/base/helmrelease.yamlcover each controller's 7-day working-set peak (#2681); resize them fromcontainer_memory_working_set_bytes{namespace="flux-system"}when Flux manages much more.- Every
${var}must resolve. From Flux 2.9 (kustomize-controller 1.9)StrictPostBuildSubstitutionsis on by default: a${var}without a default that is missing from a Kustomization'spostBuildinputs fails that Kustomization instead of becoming an empty string. Give an optional variable a default (${var:=}), or write a literal as$${var}. To check one Kustomization against its live inputs:flux --context admin@mgmt-cluster build ks <name> --path ./<spec.path> --strict-substitute. - Never hand-edit the
cluster-configConfigMap or thesourceRefon a live cluster outside ofswitch-git-source.py(or its by-hand equivalent) —git_source_repositoryis the hinge that every other Kustomization'spostBuild.substituteFromdepends on. If the Gitea deploy key orgitea-platformGitRepository needs to change, editcomponents/flux/gitea-overlay/and let Flux reconcile it. - Because Flux manages its own upgrade, a bad
helmrelease.yamlchange can leave the cluster unable to reconcile further changes (including a fix pushed to Git). Validate the chart values locally (helm templateagainst thefluxcd-community/flux2chart) before merging, and watchflux --context admin@mgmt-cluster get helmreleases -n flux-systemafter merging — if it fails, you may need directkubectl/fluxCLI access to roll back, since GitOps itself is what's broken. - A
context canceledfailure on aflux2upgrade usually heals itself. When the chart changes the helm-controller Deployment, the old helm-controller pod is replaced while it is still applying the release. The revision fails withHelm upgrade failed for release flux-system/flux2 ...: context canceled. That event does not become a Taskbase task: the Alerttaskbase-platform-flux2excludescontext canceled(#3458), andFluxNotReadyreports an upgrade that stays failed. The new pod takes the leader lease, upgrades again and deploys the next revision within about a minute (2026-07-02, 2026-10-25, twice on 2026-11-07, and 2026-11-18). Before you act, runhelm --kube-context admin@mgmt-cluster -n flux-system history flux2. Adeployedrevision on the chart version in Git after thefailedone means it has recovered: checkflux --context admin@mgmt-cluster get helmreleases -A --status-selector ready=falseand leave it. Only a release that staysfailedorpending-upgrade, or controllers that don't come back, is a stuck upgrade. For that, follow the generic Flux freeze. The Prometheus alertFluxNotReadyfires whenflux2, theflux-systemKustomization or the root Kustomization stays not Ready for 10 minutes. - A
flux2upgrade that replaces kustomize-controller cancels the health checks in flight. Any Kustomization whose health check is waiting at that moment fails withhealth check failed after <duration>: context canceled, and becomes a Taskbase task. Merging aflux2upgrade while a backup gate Job runs (a<component>-preupgradeKustomization) triggers this: on 2026-11-18 it hitharbor-preupgrade45 minutes into its gate. The Job keeps running and the new controller waits for it again, so it heals on its own. Do not delete the gate Job: that runs a new backup with the writers stopped. The checks are in Health check of another Kustomization canceled. - New cluster bootstrap: replicate the
hetzner-mgmttwo-stage pattern only if Gitea doesn't exist yet when the new cluster comes up. If Gitea is already reachable, bootstrap directly againstplatform/Gitea and skipflux/configandgitea-overlayentirely — don't copy bootstrap complexity that isn't needed.