Introduction

Several posts on this blog contain the words “managed by Flux”. The SOPS post has a whole section on how Flux decrypts secrets. The descheduler post deploys a Helm chart “through Flux”. I never explained what Flux is or how my repository is organised around it. This post fills that gap.

The short version: nothing on my cluster is deployed by hand. I do not run kubectl apply or helm install to put an application there. I change a YAML file, I push a commit, and within a few minutes the cluster looks like the commit says. If I change something by hand on the cluster, it is changed back.

That way of working is called GitOps, and Flux is the tool that does it here. I will cover the concepts first, then my actual layout, and finally the things that surprised me.

GitOps in Four Ideas

GitOps is a small set of rules. The OpenGitOps project lists four of them:

  1. Declarative. You describe the state you want (three replicas of this, version 2.4 of that), not the commands to get there.
  2. Versioned. That description lives in Git. Every change is a commit with an author, a date and a diff.
  3. Pulled. An agent inside the cluster fetches the description by itself. Nothing outside pushes to the cluster.
  4. Continuously reconciled. The agent compares the cluster with Git all the time, not only when something changes, and corrects any difference.

The third rule is the one that changes the security picture. In a classic pipeline, a CI job runs kubectl apply, so the CI system holds credentials that can modify the cluster. With a pull model, the cluster only needs read access to a Git repository. My Kubernetes API is not reachable from any CI runner, and it does not need to be.

The fourth rule is the one that changes daily life. A rollback is a git revert. An audit trail is git log. Rebuilding the cluster from nothing is “install Flux and point it at the repository”.

What Flux Is

Flux is not one program. It is a handful of controllers, each watching its own kind of object:

ControllerWatchesDoes
source-controllerGitRepository, HelmRepositoryDownloads the content (a Git commit, a chart index) and keeps a local copy
kustomize-controllerKustomizationTakes a folder from that copy, builds the manifests and applies them to the cluster
helm-controllerHelmReleaseInstalls and upgrades Helm charts, with rollback on failure
notification-controllerAlert, ProviderSends events to a chat, a webhook, a Git commit status
graph LR
    GIT[Git repository] -->|pull every minute| SRC[source-controller]
    SRC --> KC[kustomize-controller]
    KC -->|apply manifests| API[Kubernetes API]
    KC -->|creates HelmRelease| HC[helm-controller]
    HC -->|install / upgrade chart| API
    KC -.->|events| NC[notification-controller]
    HC -.->|events| NC
    NC -->|message| CHAT[Telegram]

    style GIT fill:#ae81ff,stroke:#272822,color:#fff
    style API fill:#ae81ff,stroke:#272822,color:#fff
  

Flux has no web interface. You talk to it with the flux CLI or with plain kubectl, because everything it knows is stored as Kubernetes objects.

Two Things Named Kustomization

This confused me for longer than I would like to admit. There are two different objects called Kustomization, and a Flux repository uses both.

The first one belongs to Kustomize, the tool built into kubectl. It is a plain file named kustomization.yaml that lists other files. It never reaches the cluster:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - namespace.yaml
  - deployment.yaml
  - service.yaml

The second one belongs to Flux. It is a real object stored in the cluster, and it means “take this folder from this Git repository and keep the cluster in sync with it”:

apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./flux/apps
  prune: true

The way I keep them apart: the Kustomize file is a table of contents, the Flux object is a sync job. The sync job points at a folder, and the table of contents in that folder says which files to load. Look at the apiVersion when in doubt.

Bootstrapping

Installing Flux is one command. My Git server is a self-hosted GitLab, so I use the GitLab variant:

export GITLAB_TOKEN=<YOUR_GITLAB_TOKEN>

flux bootstrap gitlab \
  --hostname=gitlab.example.com \
  --deploy-token-auth \
  --owner=homelab \
  --repository=homelab-cluster \
  --branch=main \
  --path=./flux

It does four things:

  1. It installs the controllers in the flux-system namespace.
  2. It creates a read-only deploy token so the cluster can clone the repository.
  3. It commits its own manifests into the repository, under flux/flux-system/.
  4. It creates a GitRepository and a first Kustomization that point at ./flux.

Step 3 is the elegant part. From then on Flux manages itself like any other application. A Flux upgrade is a commit that changes gotk-components.yaml, and Renovate opens that merge request for me.

One consequence: gotk-components.yaml is generated, and the next upgrade overwrites it. When I wanted to lower the CPU requests of the controllers, I did not edit that file. I added a patch in the kustomization.yaml next to it:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - gotk-components.yaml
  - gotk-sync.yaml
patches:
  - target:
      kind: Deployment
      name: (helm-controller|kustomize-controller|notification-controller)
    patch: |
      - op: replace
        path: /spec/template/spec/containers/0/resources/requests/cpu
        value: 50m

The only thing the bootstrap cannot take from Git is the key that decrypts my secrets. That is one kubectl create secret, wrapped in a just recipe, and it is the single manual step in a full rebuild.

My Repository Layout

Everything Flux reads lives in one folder:

flux/
├── kustomization.yaml            # table of contents: the four entries below
├── flux-system/                  # Flux itself (generated by bootstrap)
├── infrastructure.yaml           # sync job 1
├── infrastructure/               #   CNI, storage drivers, operators, logging
├── infrastructure-config.yaml    # sync job 2
├── infrastructure-config/        #   objects that need the operators above
├── apps.yaml                     # sync job 3
└── apps/                         #   one folder per application

There are three sync jobs, and they run in a fixed order.

Why Three Layers

Kubernetes operators extend the API with their own object types (CRDs). You cannot create a Gateway before the Gateway API types exist, and those arrive with the network plugin. If Flux applied everything in one pass on an empty cluster, half of the objects would be rejected with “no matches for kind”.

So the layers follow the dependency chain:

graph TD
    A["infrastructure: Cilium, storage drivers, database operator, backup operator, logging"] --> B["infrastructure-config: load balancer pool, Gateway, StorageClass, SnapshotClass"]
    B --> C["apps: database cluster, RSS reader, recipes, media stack, reverse proxy, ..."]

    style A fill:#ae81ff,stroke:#272822,color:#fff
    style B fill:#ae81ff,stroke:#272822,color:#fff
    style C fill:#ae81ff,stroke:#272822,color:#fff
  

The order is enforced by two fields. Here is the last layer in full:

apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: apps
  namespace: flux-system
spec:
  interval: 10m          # re-check the cluster against Git every 10 minutes
  retryInterval: 1m      # after a failure, try again sooner
  timeout: 5m
  sourceRef:
    kind: GitRepository
    name: flux-system
  path: ./flux/apps
  prune: true            # a file removed from Git is removed from the cluster
  wait: true             # Ready only when every object is healthy
  decryption:
    provider: sops
    secretRef:
      name: sops-age
  dependsOn:
    - name: infrastructure-config
  • dependsOn says “do not start before that other sync job is Ready”.
  • wait: true defines what Ready means: not “the YAML was accepted” but “every Deployment has its pods running, every Helm release is installed”.

Together they mean that applications only start once the gateway and the storage classes actually work. On a fresh cluster, the three layers come up one after the other with nobody watching.

The decryption block is how encrypted secrets in Git become normal Secrets in the cluster. The SOPS post covers it.

Adding an Application

An application is a folder. My RSS reader looks like this:

flux/apps/freshrss/
├── kustomization.yaml     # table of contents
├── namespace.yaml
├── pvc.yaml
├── deployment.yaml
├── service.yaml
└── httproute.yaml         # rss.example.com → the service

To deploy it, I add one line to the table of contents of the layer:

# flux/apps/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - postgres
  - freshrss        # ← the new line
  - mealie

Commit, push, done. To remove the application, I delete the line and the folder. Because of prune: true, Flux deletes every object that came from it.

Helm Charts

Many components ship as Helm charts. Flux handles those with two objects: where the charts come from, and which one to install.

apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
  name: descheduler
  namespace: flux-system
spec:
  interval: 12h
  url: https://kubernetes-sigs.github.io/descheduler/
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: descheduler
  namespace: flux-system
spec:
  interval: 30m
  targetNamespace: descheduler
  chart:
    spec:
      chart: descheduler
      version: "0.37.0"
      sourceRef:
        kind: HelmRepository
        name: descheduler
  upgrade:
    remediation:
      retries: 3
  values:
    kind: CronJob
    schedule: "30 1 * * *"

The values block replaces the values.yaml file you would pass to helm install. If an upgrade fails, the helm-controller rolls the release back by itself.

Day to Day

I rarely type a flux command. My just recipes cover the few I need:

just flux::status        # flux get all -A
just flux::reconcile     # do not wait 10 minutes, sync now
just flux::suspend       # stop reconciling (maintenance, debugging)
just flux::resume
just flux::revert-last   # list recent merges, git revert one, push

suspend deserves a word. Continuous reconciliation is great until you debug something by hand. You scale a Deployment to zero to look at its volume, and ten minutes later Flux scales it back up, because Git says one replica. Suspending the sync job first is the polite way to say “I know, leave it”.

Knowing What Happened

When deployment is automatic, the risk is not knowing that something was deployed. The notification-controller sends two kinds of messages to a Telegram chat:

apiVersion: notification.toolkit.fluxcd.io/v1beta3
kind: Alert
metadata:
  name: on-failure
  namespace: flux-system
spec:
  providerRef:
    name: telegram
  eventSeverity: error
  eventSources:
    - kind: Kustomization
      name: "*"
    - kind: HelmRelease
      name: "*"

A second Alert with eventSeverity: info reports every new revision that was applied. I added it later, when Renovate started merging some updates on its own. Without it, an automatic update that works is completely silent. That second alert also exposed a problem that had been running unnoticed, which brings me to the next section.

What Bit Me

Two Controllers, One Field

One of my Services has a field that another operator fills in. My Git file contained a placeholder value. The operator replaced it with the real one. Ten minutes later Flux saw a difference with Git and put the placeholder back. Then the operator fixed it again. That loop ran every ten minutes for about three weeks before the “new revision applied” messages made it visible.

Flux was doing exactly what it is built for: Git says X, the cluster says Y, so apply X. The fix is an annotation that tells Flux to create the object if it is missing and never touch it afterwards:

metadata:
  annotations:
    kustomize.toolkit.fluxcd.io/ssa: IfNotPresent

The price: edits to that object in Git no longer reach the cluster. To change it, I delete it and let Flux create it again. I wrote that down next to the annotation, because I would not remember it otherwise.

A Version Range Is a Change Without a Commit

A HelmRelease accepts a version range such as 1.20.x. I used one for my network plugin. One day the cluster was running 1.20.2 instead of 1.20.1. There was no commit, no merge request, nothing in git log. The helm-controller had found a newer chart inside the range and upgraded the component that carries all pod networking, on its own schedule.

A range breaks the second GitOps rule: the cluster changed and Git did not. Every chart version in my repository is now pinned to an exact number, and Renovate proposes the bumps as merge requests. The update still arrives, but as a commit I can read, delay or revert.

“Applied” Does Not Mean “Working”

A chart upgrade of my log database went through cleanly. The pod started, became Ready, and Flux reported success. About one minute later the new version crashed on a configuration it no longer accepted, and kept crashing. From Flux’s point of view the release was installed, so there was no rollback and no alert. Logs simply stopped arriving.

wait: true and Helm’s health checks look at the state right after the change. They do not watch the application for the next hour. Flux tells me that Git was applied. Whether the application does its job is a separate question, and it needs separate monitoring.

Prune Deletes What You Stop Declaring

prune: true is what keeps the cluster clean. It is also a loaded gun for the few objects that must outlive their folder. When I migrated my storage driver, the old namespace had to stay: every existing volume holds a reference to a Secret inside it, and that reference cannot be changed. Deleting the folder would have removed the namespace, and with it the ability to mount any existing volume.

For those cases Flux has a second annotation:

metadata:
  annotations:
    kustomize.toolkit.fluxcd.io/prune: disabled

Before removing a folder from a Flux repository, I now ask what else points at the objects inside it.

What About Argo CD?

Argo CD is the other well-known GitOps tool. I have only run Flux on this cluster, so this is not a comparison from experience. The differences that are easy to verify:

FluxArgo CD
InterfaceCLI and Kubernetes objectsWeb UI, CLI and Kubernetes objects
ShapeSeveral small controllersOne application with a server and a UI
SOPS secretsBuilt into the kustomize-controllerThrough a plugin
HelmNative Helm releases (helm list shows them)Renders the chart to plain manifests, then applies them

If you want to see your applications on a dashboard and click “sync”, look at Argo CD. I wanted something that stays out of the way, and the built-in SOPS support matched how my secrets were already stored.

Key Takeaways

ConceptWhat I Learned
Pull, not pushThe cluster reads Git; nothing outside needs write access to the cluster
Two KustomizationsThe Kustomize file is a table of contents, the Flux object is a sync job
LayersdependsOn + wait: true bring CRDs up before the objects that use them
Flux manages FluxBootstrap commits its own manifests; patch them, never edit the generated file
Pin exact versionsA version range lets the cluster change without a commit
Shared fieldsWhen another controller owns a field, ssa: IfNotPresent stops the tug-of-war
Prune with careRemoving a folder removes its objects; prune: disabled protects the exceptions
Applied ≠ workingFlux reports that Git was applied, not that the application is healthy an hour later

Conclusion

Flux moved the question “what is running on my cluster?” from the cluster to a Git repository. That sounds like a small shift. In practice it means I can read the answer on my phone, review a change before it happens, and undo it with a revert.

It did not remove the need to understand what I deploy. Each of the four surprises above was Flux doing precisely what I had told it to do. What GitOps gave me is that each of those mistakes was written down, in a commit, with a date, which made them a lot easier to find than something I had typed in a terminal months ago.

This post is the base for the ones that follow. The next posts about this cluster will say “managed by Flux” again, and now there is a page to link to.


Useful Resources: