Kubernetes · GitOps

Who Deploys the Deployer? Terraform-Bootstrapped FluxCD

Terraform installs the six Flux controllers on a fresh cluster and seeds per-cluster GitOps config from templates; Flux then manages the cluster and itself.

  • FluxCD
  • Terraform
  • Kustomize
  • Helm
  • GitHub App
  • Workload Identity
  • External Secrets
  • Istio

// Why this matters

If you want to bootstrap FluxCD with Terraform on every new cluster, you need to solve a small but sharp problem first: Flux deploys everything from Git, but something has to put Flux there. Without GitOps, deployment is manual kubectl with no audit trail; with it, every change is a commit and every rollback is a revert. The only question is how the first commit gets wired up repeatably.

The second motivation is scale. When a platform onboards many clusters, the bootstrap must be a pipeline, not a runbook. It has to produce the same controllers, the same identity wiring and the same directory layout every time, and it must be safe to re-run without trampling the customisations a team made after day one.

This is stage three of From Form to Running Cluster: Self-Service Team Onboarding: the last step after the cluster exists and the autoscaler is registered (see One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling). Below is the technique, with the real traps.

// The problem

The chicken-and-egg is literal. Flux Kustomizations and HelmReleases are Kubernetes resources reconciled by Flux controllers, so the controllers cannot be installed by Flux. Something external must install CRDs and controllers, create the GitRepository and root Kustomization, and commit the generated sync manifests back to the repository.

A subtler version appears with secrets. The credential the root GitRepository uses to read the repo is usually delivered by an ExternalSecret, but the External Secrets operator itself is installed by Flux. On a brand-new cluster the first sync fails because the secret does not exist yet and cannot be created until Flux syncs.

The third problem is re-runs. If the bootstrap workflow regenerates the cluster directory from templates every time it runs, any customisation made since the first run (a patched HelmRelease, an added application) is overwritten. And the controllers themselves need production tuning (concurrency, memory, scheduling onto system nodes) that defaults do not provide.

// The solution

Terraform is the external actor, and it does three things in a fixed order. First it creates the flux-system namespace and seeds the GitHub App credential secret, with ignore_changes = all so the External Secrets operator and Flux own it afterwards. Second it runs flux_bootstrap_git, which installs CRDs and the controllers, creates the GitRepository and Kustomization, and commits gotk-components.yaml and gotk-sync.yaml. Third it applies controller patches through the resource's kustomization_override, so they are part of the committed flux-system/kustomization.yaml.

Config generation is separate and happens in the workflow before Terraform. A job copies a shared template directory into clusters/<env>/<cluster>/, prunes optional directories according to feature flags (centralised monitoring, HA, mesh mode), and runs envsubst on a single templated Kustomization that carries all cluster-specific values in postBuild.substitute. The result is opened as a pull request and auto-merged, so the generated config is reviewed history, not a side effect.

There are two sources of truth and the split is deliberate. flux-system/kustomization.yaml belongs to Terraform and is regenerated on every apply; everything under infrastructure-base-overrides/ belongs to the workflow and is generated once, then protected by BOOTSTRAP_LOCK.md. On the second run the config job sees the lock and skips generation, while Terraform still runs and reconciles the controller patches.

Authentication uses a GitHub App rather than a personal token, with a per-cluster Vault key that lets a cluster fall back to a PAT during migration. Every controller gets its own workload identity via a service account annotation, so there are no static cloud credentials anywhere. I rejected the flux bootstrap CLI in CI because it is imperative and hard to put under plan review, and rejected storing the app key in the repo even encrypted because rotation then needs a commit per cluster.

How it flows flow1. Trigger → 2. Prepare → 3. Lock check → 4. Generate config → 5. PR to GitOps repo → 6. Terraform apply → 7. Controller patches → 8. Create lock → 9. Steady state01Trigger02Prepare03 · GATELock check04Generate config05PR to GitOps repo06Terraform apply07Controller patches08Create lock09Steady state
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Triggerafter autoscaling, or manually; concurrency per team and environment
  2. Prepareread 20+ Vault values, resolve six controller identities
  3. Lock check gateif a bootstrap lock exists, skip config generation
  4. Generate configcopy template base, prune optional directories, substitute variables
  5. PR to GitOps repoauto-merged; repeated for the HA secondary
  6. Terraform applymatrix over lower, upper, primary, secondary
  7. Controller patchesconcurrency, resource limits, affinity, identity annotations
  8. Create lockcommitted per cluster
  9. Steady stateFlux reconciles every 60 seconds; rotation flows through Vault
WorkflowGitOps repoTerraformClusterlock exists? if not, template + envsubst, open PRPR auto-mergedmatrix apply per clusterseed namespace + app credentialflux_bootstrap_git + controller patchesFlux reads clusters/env/cluster every 60scommit BOOTSTRAP_LOCK.md
Bootstrap sequence for one cluster. Config generation and Terraform are separate stages; the lock decides whether generation runs at all.
Terraform-ownedflux-system/kustomizationgotk-components.yamlgotk-sync.yamlWorkflow-owned (once)infra-bootstrap.yamloverrides/ patchesBOOTSTRAP_LOCK.mdShared base (read-only)HelmReleases with ${vars}Common Kustomizations
Who owns what in the cluster directory. Ownership boundaries decide which files may be regenerated.

// Before you start

  • A Kubernetes cluster reachable from your CI runner (private clusters need a peered or self-hosted runner), with workload identity enabled.
  • A GitOps repository the CI identity can open and auto-merge pull requests in, and a GitHub App installed on it with contents read/write.
  • Terraform 1.9+ with providers fluxcd/flux (~> 1.4), hashicorp/kubernetes, integrations/github and hashicorp/vault.
  • The Flux CLI for local verification, envsubst and yq in the runner image.
  • One user-assigned managed identity per Flux controller, federated to the cluster OIDC issuer.
  • Vault keys holding the app id and private key at a path your CI can read.

// Step-by-step implementation

  1. 01 Seed the namespace and the GitHub App credential before bootstrap

    Create the flux-system namespace and the credential Secret from Terraform ahead of flux_bootstrap_git. This resolves the secret chicken-and-egg: the root GitRepository can read the repo on its first sync, and later the External Secrets operator adopts the Secret (owner creation policy) once Flux has installed it.

    Use ignore_changes = all on both resources so Terraform never fights the operator, and do lookups with data sources so a re-run on an existing cluster imports rather than fails. A 404 from a Kubernetes data source returns an empty uid with no error, which is the trick that makes the existence check work.

  2. 02 Bootstrap Flux with Terraform and apply controller patches in the same resource

    This is the core step. flux_bootstrap_git installs the controllers, commits gotk-components.yaml and gotk-sync.yaml under the cluster path, and accepts a kustomization_override that becomes the committed flux-system/kustomization.yaml. Putting patches there means they are applied by Flux itself on every reconcile and by Terraform on every apply.

    Choose components_extra to add the image automation controllers if you want Flux to commit image tag updates back to Git. Give the resource generous create and update timeouts: pods need to schedule on system nodes, and on update the image automation controller on other clusters may push commits to the same repo while the health check runs, which makes the check race a moving HEAD.

  3. 03 Schedule controllers onto system nodes and label them for workload identity

    Controllers must not compete with application pods. Add a patch with a toleration for the system taint and a required node affinity on the system node group label, targeting every Deployment in flux-system. A second patch adds the pod label that tells the workload identity webhook to inject a token.

    Set explicit resource requests and limits per controller class. The reconcilers that render charts need more memory than the image scanners, and without limits the first large chart can OOM the helm controller. Enabling the controller OOM-watch feature gate restarts it gracefully before a kill.

  4. 04 Generate the per-cluster config from templates, pruning by feature flag

    Keep one template tree and generate each cluster's directory from it in the workflow. Copy the base overrides, then remove optional parts based on flags read from Vault: no monitoring sub-tree when centralised monitoring is off, no health-check routes when HA is off, no ambient-mesh components when the mode is managed. Every removal must also remove the matching line from the parent kustomization.yaml, or Kustomize fails on a missing path.

    Substitution happens once, with envsubst, on a single templated Kustomization. Everything cluster-specific (identity client ids, key vault URL, domain, channel names) is a postBuild.substitute value, so the shared base HelmReleases stay generic (see the Flux variable substitution model). Do not substitute into the base itself; keep it variable-driven.

  5. 05 Open an auto-merged pull request, then apply Terraform per cluster with a matrix

    Generated config is committed through a branch named after the run and merged automatically. That gives you a reviewable diff of exactly what was generated and a clean commit for Flux to read; Terraform must not run until the merge lands, or flux_bootstrap_git will bootstrap against a path that does not exist.

    Terraform providers cannot be iterated with for_each, so run the same root once per cluster with a workflow matrix: lower, upper, and for HA the secondary of each, each with its own state key. The secondary passes is_secondary and a -secondary state suffix so the module reads suffixed Vault keys. Reuse the same plan-gated reusable workflow as everywhere else.

  6. 06 Write the bootstrap lock so re-runs only reconcile controller patches

    After a successful apply, commit BOOTSTRAP_LOCK.md in the cluster directory. On every later run the config job checks for the file and skips generation entirely. Terraform still applies, so controller patches (which you may tune over time) keep converging, but a team's customised overrides and applications are never regenerated.

    To regenerate on purpose (new template components, corrupted config, switching mesh mode), delete the file in a commit and re-run. With HA there is one lock per cluster, checked independently, so you can regenerate one cluster without touching the other.

// How to verify it works

  • kubectl get pods -n flux-system shows all six controllers Running on system nodes (-o wide).
  • flux get kustomizations -A shows the root and infra-bootstrap as Ready, and flux get sources git -A shows the repo fetched at the expected revision.
  • kubectl -n flux-system get deploy helm-controller -o jsonpath="{.spec.template.spec.containers[0].args}" lists --concurrent=10 and the OOM watch flags.
  • kubectl -n flux-system get sa kustomize-controller -o yaml carries the workload identity annotations, and the pods have the identity label.
  • Re-run the workflow. Expected: the config job reports the lock and skips generation, Terraform plans no changes (or only patch drift), and no new pull request appears.
  • Delete a Flux-managed test object and wait one interval; it must reappear.

// Design decisions and trade-offs

  • Bootstrap lock: the first run generates, later runs only reconcile controller patches; delete the lock to regenerate.
  • Template system with conditional pruning by feature flag (HA, monitoring, mesh mode).
  • Git authentication via GitHub App, with PAT fallback gated per cluster by a Vault key.
  • Workload identity on every controller instead of static cloud credentials.
  • Controller settings are Terraform patches rather than a template so they can be reconciled on every run.
  • HA uses separate state per cluster and separate key suffixes for the secondary.

// Pitfalls and lessons learned

  • Letting Terraform and the workflow both own flux-system/kustomization.yaml. It is regenerated by Terraform on every apply; never edit it in Git.
  • Forgetting to remove the matching line from the parent kustomization when pruning a directory. Kustomize then fails the whole reconcile on a missing path.
  • Running Terraform before the generated pull request merges. Flux bootstraps against a path that does not exist and reports a confusing not-found.
  • Racing health checks on update when image automation controllers on other clusters push to the same repo. Allow a long update timeout.
  • No lock, or lock checked after generation. The first re-run silently wipes team customisations.
  • Static cloud credentials in the cluster. Use per-controller workload identity instead; it also makes rotation a Vault-only operation.
  • Substituting variables into the shared base. Keep the base generic and push all cluster values through postBuild.substitute.

// Frequently asked questions

How do I bootstrap FluxCD with Terraform instead of the flux CLI?

Use the flux_bootstrap_git resource from the Flux provider: it installs CRDs and controllers, creates the GitRepository and Kustomization, and commits the sync manifests. Seed any pre-sync secrets with the Kubernetes provider first.

How do I patch Flux controllers when using Terraform?

Pass a kustomization_override to flux_bootstrap_git with a patches list. The patches are committed in flux-system/kustomization.yaml and applied on every reconcile.

Why use a GitHub App instead of a personal access token for Flux?

App tokens are short-lived, scoped to the repository, not tied to a person, and rotate without touching each cluster.

How do I stop a bootstrap workflow overwriting customised cluster config?

Commit a lock file after the first successful bootstrap and skip config generation when it exists. Keep controller patches in Terraform so they still converge.

Can I run the same Terraform root for many clusters?

Providers cannot use for_each, so run the root once per cluster with a matrix, giving each its own state key suffix.

// The outcome

Six controllers per cluster, reconciling every 60 seconds, with no hand-run bootstrap.

// Where to take it next

// Keep reading