TExcelTAD
Home › GitOps: Argo CD & Flux › The Kustomize Controller

The Kustomize Controller

A Flux Kustomization takes an artifact from a source, builds one path in it with Kustomize, and keeps the result applied: server-side apply, pruning, health checks, dependencies and variable substitution, all configured on one object. It is Flux's equivalent of an Argo CD Application for plain YAML and Kustomize content.

The object

yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: linkly-staging
  namespace: flux-system
spec:
  interval: 10m            # re-apply (and correct drift) at least this often
  retryInterval: 2m        # after a failure, try again sooner
  timeout: 3m              # how long to wait for health before reporting failure
  sourceRef: {kind: GitRepository, name: linkly-deploy}
  path: ./apps/staging
  prune: true              # delete objects removed from the source (tracked in .status.inventory)
  wait: true               # wait for ALL applied objects to become ready
  targetNamespace: linkly-staging
  dependsOn:
    - name: infrastructure # don't start until that Kustomization is Ready
  postBuild:
    substitute: {cluster_env: staging}
    substituteFrom:
      - {kind: ConfigMap, name: cluster-vars}

See exactly what it will apply

flux build kustomization runs the controller's build logic locally (Kustomize plus Flux's post-build substitution and labels) and --dry-run keeps it from contacting a cluster. This is the Flux counterpart of rendering a chart before Argo CD sees it:

bash · try it yourself
mkdir -p linkly-deploy/apps/staging && cd linkly-deploy
cat > apps/staging/config.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: linkly-config
data:
  LOG_LEVEL: debug
  BASE_URL: https://lnk.${cluster_env}.example.com
  REGION: ${region:=eu-west-1}
EOF
printf 'resources: [config.yaml]\n' > apps/staging/kustomization.yaml
flux create kustomization linkly-staging --source=GitRepository/linkly-deploy \
  --path=./apps/staging --prune=true --interval=10m --target-namespace=linkly-staging --export > ks.yaml
yq -i '.spec.postBuild.substitute.cluster_env = "staging"' ks.yaml
flux build kustomization linkly-staging --path ./apps/staging --kustomization-file ./ks.yaml --dry-run
apiVersion: v1
data:
  BASE_URL: https://lnk.staging.example.com
  LOG_LEVEL: debug
  REGION: eu-west-1
kind: ConfigMap
metadata:
  labels:
    kustomize.toolkit.fluxcd.io/name: linkly-staging
    kustomize.toolkit.fluxcd.io/namespace: flux-system
  name: linkly-config
  namespace: linkly-staging
---

Three things happened beyond kustomize build: the namespace came from targetNamespace; ${cluster_env} was substituted and ${region:=eu-west-1} fell back to its default; and the controller added the kustomize.toolkit.fluxcd.io/name and …/namespace labels it uses to track ownership. Substitution is plain text replacement after the build, so keep it for a few cluster-level values (environment name, region, domain) and use overlays for everything structural. Escape a literal $ as ${...}, or turn substitution off for one object with the annotation kustomize.toolkit.fluxcd.io/substitute: disabled.

Ordering with dependsOn

Flux has no sync waves inside a Kustomization (it applies CRDs and Namespaces first, then everything else, in one server-side apply). Ordering between groups of objects is done by splitting them into several Kustomizations and chaining them with dependsOn. A dependent waits until its dependencies are Ready, which with wait: true means their objects are healthy, not just applied.

python · try it yourself
kustomizations = {
    "crds":           {"dependsOn": [],                 "ready_after": 1},
    "infrastructure": {"dependsOn": ["crds"],           "ready_after": 2},
    "linkly-redis":   {"dependsOn": ["infrastructure"], "ready_after": 2},
    "linkly":         {"dependsOn": ["infrastructure", "linkly-redis"], "ready_after": 1},
    "monitoring":     {"dependsOn": ["crds"],           "ready_after": 3},
}

ready, started = set(), {}
for minute in range(1, 9):
    for name in sorted(kustomizations):
        ks = kustomizations[name]
        if name in started or not all(d in ready for d in ks["dependsOn"]):
            continue
        started[name] = minute
    finished = [n for n, t in started.items() if n not in ready and minute - t + 1 >= kustomizations[n]["ready_after"]]
    events = [f"start {n}" for n, t in started.items() if t == minute] + [f"Ready {n}" for n in sorted(finished)]
    ready.update(finished)
    if events:
        print(f"minute {minute}: " + ", ".join(events))
    if len(ready) == len(kustomizations):
        break
minute 1: start crds, Ready crds
minute 2: start infrastructure, start monitoring
minute 3: Ready infrastructure
minute 4: start linkly-redis, Ready monitoring
minute 5: Ready linkly-redis
minute 6: start linkly, Ready linkly

Independent chains (monitoring) proceed in parallel; linkly waits for both of its dependencies. If linkly-redis never becomes Ready, linkly is never applied, the same blocking behaviour as Argo CD waves, made explicit in the object graph. flux tree kustomization flux-system and flux get kustomizations show the graph and the states on a live cluster.

Health checks

  • wait: true checks every applied object using kstatus (the same readiness rules as kubectl wait: Deployments rolled out, Jobs complete, objects with a Ready condition true).
  • Instead of wait, healthChecks lists specific objects to wait for, and healthCheckExprs (newer releases) defines readiness of custom resources with CEL expressions.
  • A Kustomization whose objects don't become healthy within timeout reports Ready=False with a HealthCheckFailed reason; dependents stay blocked.

Multi-tenancy: whose permissions?

By default kustomize-controller applies with its own (cluster-admin-like) ServiceAccount. Setting spec.serviceAccountName makes it impersonate that ServiceAccount, so a team's Kustomization can only do what the team's RBAC allows in its namespace. The Flux docs' multi-tenancy guide combines this with a flag that forces impersonation for all tenants (--default-service-account) and with flux create tenant, which generates the namespace, ServiceAccount and RoleBinding:

bash · try it yourself
flux create tenant linkly --with-namespace=linkly-staging --with-namespace=linkly-prod --export > tenant.yaml
yq -N '.kind + "/" + .metadata.name + (.metadata.namespace // "" | select(. != "") | " in " + .)' tenant.yaml
kubeconform -strict -summary tenant.yaml
Namespace/linkly-staging
ServiceAccount/linkly in linkly-staging
RoleBinding/linkly-reconciler in linkly-staging
Namespace/linkly-prod
ServiceAccount/linkly in linkly-prod
RoleBinding/linkly-reconciler in linkly-prod
Summary: 6 resources found in 1 file - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0

This is Flux's answer to Argo CD Projects: restrictions come from ordinary Kubernetes RBAC rather than from a tool-specific object.

Test yourself

In a Flux Kustomization, what does ${region:=eu-west-1} in a manifest become when no region variable is defined?

  1. An empty string
  2. eu-west-1
  3. The literal text ${region:=eu-west-1}
  4. A build error

How do you make the linkly Kustomization wait until Redis is healthy?

  1. A sync-wave annotation
  2. Put Redis in its own Kustomization with wait: true and add it to linkly's dependsOn
  3. Use a PreSync hook
  4. Set interval: 0

What does spec.serviceAccountName on a Kustomization do?

  1. Runs the controller under that account
  2. Makes kustomize-controller impersonate that ServiceAccount when applying, limiting it to that account's RBAC
  3. Creates the ServiceAccount
  4. Pulls images with it