Skip to content

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:

  1. terraform/environments/hetzner-mgmt-cluster/2-components/main.tf installs the flux2 Helm chart directly and creates an initial GitRepository (bootstrap-cluster, see cluster/hetzner-mgmt/flux/config/gitrepository.yaml) pointing at this repository on GitHub, authenticated via a github-auth secret. The cluster-config ConfigMap's git_source_repository key starts out pointing at this GitRepository.
  2. Once openbao and gitea are deployed and healthy, the flux-system-gitea-overlay Kustomization (components/flux/gitea-overlay) applies: it creates a gitea-platform GitRepository pointing at ssh://git@gitea.prod.skatzi.com/Skatzi/platform.git (deploy key synced from OpenBao via ExternalSecret), then runs the switch-to-gitea-source Job, which runs switch-git-source.py gitea-platform: once gitea-platform is Ready it patches the cluster-config ConfigMap and the hetzner-mgmt-cluster Kustomization's sourceRef to point at gitea-platform instead. 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/platform to https://github.com/${github_owner}/${github_repository}.git (DunkRing/bootstrap-cluster, the same cluster-config values the bootstrap-cluster GitRepository 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 --mirror and force (+refs/heads/*, +refs/tags/*; services/mirror/mirror_push.go in Gitea 1.25.5). GitHub's ${github_branch} (main) therefore always equals Gitea's main: 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 the gitea-push-mirror Flux Kustomization in cluster/hetzner-mgmt/gitea/kustomization.yaml (dependsOn: [gitea]). The CronJob gitea/github-push-mirror runs reconcile-push-mirror.py every 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 with 401 on 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, or Operation not permitted from 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 answers 401 even to a valid token (#2500). So a 401, 500, 502 or 503 on that first call is retried the same way while Gitea's unauthenticated /api/healthz does not answer 200 with status: 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 the github-mirror-token ExternalSecret in the gitea namespace syncs them hourly into the Secret of the same name. Property github-mirror-token (key token) is a fine-grained GitHub personal access token limited to DunkRing/bootstrap-cluster with 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. Property gitea-token (key gitea-token) is a Gitea access token with scope write:repository of an account with admin rights on Skatzi/platform, which the reconciler sends as Authorization: token. The Gitea backup gate and restore drill send the same token in their smoke check, through the gitea-token ExternalSecret in gitea-scratch. Write one property with bao kv patch so 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; GiteaPushMirrorFailing reports 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: GiteaPushMirrorFailing fires 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/main and git ls-remote https://github.com/DunkRing/bootstrap-cluster.git refs/heads/main (both need read access) print the same SHA. Settings → Repository → Mirror settings in Gitea shows the last update and any error, and kubectl --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 Ready after that fetch;
  • (to GitHub only) gitea-platform has no fetched artifact, or bootstrap-cluster's commit is not the same as, or ahead of, the last commit Flux fetched from gitea-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 apply of hetzner-mgmt-cluster/2-components rewrites cluster-config: it resets git_source_repository to bootstrap-cluster and drops the hold annotation. That is no different from before this switch existed; the next switch-to-gitea-source run switches back to Gitea.
  • The templates and the Job need the python:3.15.2-alpine image 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:

  1. kubectl --context admin@mgmt-cluster -n flux-system get cronjob git-source-fallback git-source-restore configmap git-source-switch shows all three.
  2. Run git-source-fallback (above). Its log ends with switched Flux to bootstrap-cluster (hold set); kubectl --context admin@mgmt-cluster -n flux-system get configmap cluster-config -o yaml shows git_source_repository: bootstrap-cluster and the hold; flux --context admin@mgmt-cluster get kustomizations shows the source revisions main@sha1:<sha> unchanged.
  3. Wait for the next switch-to-gitea-source Job (up to 15 minutes) or run kubectl --context admin@mgmt-cluster -n flux-system get jobs; its log says the hold is set, and the source stays on GitHub.
  4. Run git-source-restore. Its log ends with switched 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/): the taskbase Provider signs each event with the token key of the taskbase-flux-webhook secret. An ExternalSecret syncs that key from OpenBao hetzner-mgmt/taskbase/flux-webhook, property secret — the value Taskbase verifies with. The address and OpenBao path are patched in cluster/hetzner-mgmt/flux/taskbase-alerts/kustomization.yaml.
  • One Alert per source repository (cluster/hetzner-mgmt/flux/taskbase-alerts/alert.yaml): Taskbase needs the repository the failing object comes from, so each Alert sets eventMetadata cluster (from ${cluster_name}) and repository. taskbase-platform (Skatzi/platform) covers the root hetzner-mgmt-cluster Kustomization, every platform Kustomization, and the HelmReleases in each namespace that holds one, except flux-system/flux2; taskbase-platform-flux2 covers flux2 with exclusionList: ['context canceled'], because an exclusionList applies to a whole Alert and on taskbase-platform would also mute a backup gate's canceled health check; taskbase-taskbase (Skatzi/taskbase), taskbase-emiliero (Skatzi/emiliero) and taskbase-helloweekly (Emmalia/Helloweekly) cover those repositories' Kustomizations. botyard-control has no Alert, because Dupondforge/botyard-control is 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. taskbase in cluster/hetzner-mgmt/taskbase-prod/kustomization.yaml); a patch in cluster/hetzner-mgmt/kustomization.yaml labels every other one platform.

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 same flux2 release, so once the new chart is deployed, raise its pins to match in a follow-up pull request (the module default also covers webshop, which runs the same chart from Git): version of helm_release.flux2 in terraform/environments/hetzner-mgmt-cluster/2-components/main.tf and the flux_version default in terraform/modules/hetzner/talos-cluster/components/variables.tf. Otherwise a terraform apply downgrades Flux until helm-controller reconciles again. This is self-referential — the running kustomize-controller and helm-controller apply the change to themselves. Check the Flux release notes for CRD changes between versions. The flux2 chart renders its CRDs from templates/, so Helm upgrades them with the release and also rolls them back with it; crds: CreateReplace only governs a chart's crds/ directory. Before a Flux minor, run the pre-flight: a version still in a CRD's live status.storedVersions must be in the target chart's spec.versions (Flux 2.9 removed notification.toolkit.fluxcd.io/v1beta2 and image.toolkit.fluxcd.io/v1beta2). Chart 2.20.0 (Flux 2.10) makes v1 the storage version of Alert and Provider, 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 on status.storedVersions, so the upgrade rolls forward only.
  • flux2 values are per controller. The fluxcd-community chart has no top-level controllers, resources or securityContext; Helm accepts such keys and ignores them. Set them under sourceController, kustomizeController, helmController, notificationController, imageReflectionController and imageAutomationController (helm show values flux2 --repo https://fluxcd-community.github.io/helm-charts --version <v>), and check with helm template that they reach the Deployments. The requests in components/flux/base/helmrelease.yaml cover each controller's 7-day working-set peak (#2681); resize them from container_memory_working_set_bytes{namespace="flux-system"} when Flux manages much more.
  • Every ${var} must resolve. From Flux 2.9 (kustomize-controller 1.9) StrictPostBuildSubstitutions is on by default: a ${var} without a default that is missing from a Kustomization's postBuild inputs 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-config ConfigMap or the sourceRef on a live cluster outside of switch-git-source.py (or its by-hand equivalent) — git_source_repository is the hinge that every other Kustomization's postBuild.substituteFrom depends on. If the Gitea deploy key or gitea-platform GitRepository needs to change, edit components/flux/gitea-overlay/ and let Flux reconcile it.
  • Because Flux manages its own upgrade, a bad helmrelease.yaml change can leave the cluster unable to reconcile further changes (including a fix pushed to Git). Validate the chart values locally (helm template against the fluxcd-community/flux2 chart) before merging, and watch flux --context admin@mgmt-cluster get helmreleases -n flux-system after merging — if it fails, you may need direct kubectl/flux CLI access to roll back, since GitOps itself is what's broken.
  • A context canceled failure on a flux2 upgrade 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 with Helm upgrade failed for release flux-system/flux2 ...: context canceled. That event does not become a Taskbase task: the Alert taskbase-platform-flux2 excludes context canceled (#3458), and FluxNotReady reports 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, run helm --kube-context admin@mgmt-cluster -n flux-system history flux2. A deployed revision on the chart version in Git after the failed one means it has recovered: check flux --context admin@mgmt-cluster get helmreleases -A --status-selector ready=false and leave it. Only a release that stays failed or pending-upgrade, or controllers that don't come back, is a stuck upgrade. For that, follow the generic Flux freeze. The Prometheus alert FluxNotReady fires when flux2, the flux-system Kustomization or the root Kustomization stays not Ready for 10 minutes.
  • A flux2 upgrade that replaces kustomize-controller cancels the health checks in flight. Any Kustomization whose health check is waiting at that moment fails with health check failed after <duration>: context canceled, and becomes a Taskbase task. Merging a flux2 upgrade while a backup gate Job runs (a <component>-preupgrade Kustomization) triggers this: on 2026-11-18 it hit harbor-preupgrade 45 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-mgmt two-stage pattern only if Gitea doesn't exist yet when the new cluster comes up. If Gitea is already reachable, bootstrap directly against platform/Gitea and skip flux/config and gitea-overlay entirely — don't copy bootstrap complexity that isn't needed.