KUBERNETES · INFRASTRUCTURE AS CODE · GITOPS
Tofu Controller
Running Terraform and OpenTofu inside Kubernetes
Writing Terraform is the easy part. The harder question is where that code runs, when it runs, and with whose permissions. Tofu Controller answers this from the Kubernetes side. This guide covers what it is, how to install it, the patterns people build with it, and the things you only find out in production.
Contents
- Terraform needs somewhere to run
- What Tofu Controller is
- How the architecture works
- Installation
- Your first working example
- The four adoption models
- Field reference
- Practical scenarios, with YAML
- Design patterns
- A worked example
- Where it fits
- When not to use it
- How it compares
- What to know before production
- Checklist and resources
01. Terraform needs somewhere to run
You have written a Terraform module. Someone now has to run it. In practice there are three answers, and each one hurts somewhere different.
From a laptop
What it gives you: Fast, nothing to set up
What it costs you: State lives on one machine, no concurrency control, no trail
A CI/CD pipeline
What it gives you: Familiar, keeps logs, remote state
What it costs you: One job per request, the pipeline identity grows over time, queueing is your problem
A Kubernetes controller
What it gives you: Continuous reconciliation, drift detection, one permission model
What it costs you: Needs Kubernetes, adds an operational surface
The third option turns Terraform from a job you trigger into a state you declare. Tofu Controller is one way to do that.
02. What Tofu Controller is
Tofu Controller is an infrastructure as code controller for Flux. It reconciles Terraform and OpenTofu resources the GitOps way. You write an object into Kubernetes, the controller plans it, applies it, and reports back through that object.
The project started inside Weaveworks as tf-controller. After Weaveworks shut down it moved to the flux-iac organisation and took the name Tofu Controller. It is Apache 2.0 licensed, community maintained, and actively released.
KEY IDEA
Terraform becomes a Kubernetes resource. In the same way a Deployment is responsible for keeping three replicas alive, a Terraform object becomes responsible for keeping your infrastructure in the shape you described.
What it actually solves
- It gives Terraform a durable, auditable place to run.
- It notices drift, meaning the gap between what the code says and what the cloud actually looks like.
- It splits plan from apply so you can put a human decision in between.
- It writes Terraform outputs into Kubernetes Secrets, so applications in the cluster can consume them directly.
- It runs each job in its own pod, which gives you a soft isolation boundary between teams.
03. How the architecture works
Four pieces, each with one job.
- Source controller: Fetches the code from a GitRepository, OCIRepository or Bucket.
- Terraform resource: Describes the request: which code, which inputs, which state, which approval model.
- Tofu Controller: Watches the resource, starts a runner pod when there is work, writes the result back into status.
- Runner pod: Does the actual work. init, plan and apply happen here. It talks to the controller over gRPC.
A single reconciliation loop looks like this:
- Source controller pulls the code and produces a revision.
- The controller sees the Terraform resource and starts a runner pod.
- The pod loads the code and the variables, then runs init and plan.
- Depending on the approval model it either applies straight away or waits.
- Results and any outputs are written back, then the pod exits.
- The loop repeats on the configured interval, which is how drift gets caught.
WATCH OUT
Network requirements are easy to miss. Runner pods serve gRPC on port 30000, and the controller needs port 80 to reach the Source and Notification controllers. In a restricted network this is the first thing to check.
04. Installation
Prerequisites
- A running Kubernetes cluster.
- Flux v2.0 or later. Not just the CLI, the controllers have to be installed in the cluster.
- A state backend. The Kubernetes Secret backend works for experiments, but S3, Azure Blob or GCS is what you want in production.
With Helm, the usual route
helm repo add tofu-controller https://flux-iac.github.io/tofu-controller
helm repo updatehelm upgrade -i tofu-controller tofu-controller/tofu-controller \
--namespace flux-systemStraight from a manifest
kubectl apply -f \
https://raw.githubusercontent.com/flux-iac/tofu-controller/main/docs/release.yamlPinned to a version
export TF_CON_VER=v0.16.4 # check the releases page for the current onekubectl apply -f https://github.com/flux-iac/tofu-controller/releases/download/\
${TF_CON_VER}/tf-controller.crds.yaml
kubectl apply -f https://github.com/flux-iac/tofu-controller/releases/download/\
${TF_CON_VER}/tf-controller.rbac.yaml
kubectl apply -f https://github.com/flux-iac/tofu-controller/releases/download/\
${TF_CON_VER}/tf-controller.deployment.yamlConfirming it came up
kubectl -n flux-system get pods -l app=tofu-controller
kubectl get crd terraforms.infra.contrib.fluxcd.io05. Your first working example
Two objects are enough. One says where the code comes from, the other says what to do with it.
the source
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
name: helloworld
namespace: flux-system
spec:
interval: 30s
url: https://github.com/flux-iac/helloworld
ref:
branch: mainthe request
apiVersion: infra.contrib.fluxcd.io/v1alpha2
kind: Terraform
metadata:
name: helloworld
namespace: flux-system
spec:
interval: 1m
approvePlan: auto # plan, then apply without asking
path: ./
sourceRef:
kind: GitRepository
name: helloworld
namespace: flux-systemwatching it
kubectl -n flux-system get terraform helloworld
kubectl -n flux-system describe terraform helloworld06. The four adoption models
The project documents four ways to adopt it. Knowing which one you are in makes every later decision easier.
Full automation
What it does: Manages infrastructure end to end, from provisioning through enforcement
When to pick it: Greenfield environments defined entirely in code
Hybrid
What it does: Brings only selected parts of an existing setup under GitOps
When to pick it: Gradual migration of infrastructure that was built by hand
State enforcement
What it does: Takes an existing state file as it is and enforces it
When to pick it: Handing over control without rewriting the code
Drift detection only
What it does: Watches and reports differences, changes nothing
When to pick it: Environments where automatic change is not trusted yet
KEY IDEA
The most common mistake is starting at full automation. Beginning with drift detection only, and watching it for a few weeks, is the cheapest way for a team to build trust in the tool.
07. Field reference
The fields you will actually reach for, and what they do.
approvePlan: The approval model. auto plans and applies. Empty waits. A plan id applies only that plan.path: Directory holding the Terraform files. Defaults to the root of the source.sourceRef: Where the code comes from: GitRepository, OCIRepository or Bucket.interval: How often to reconcile. This is also your drift check frequency.vars: Input variables given inline.varsFrom: Variables read from a Secret or ConfigMap, optionally filtered by key.writeOutputsToSecret: Writes Terraform outputs into a Kubernetes Secret.backendConfig: State backend settings.destroyResourcesOnDeletion: Destroys the real resources when the object is deleted.dependsOn: Dependencies on other Terraform objects, which sets the ordering.healthChecks: TCP or HTTP checks run after apply.runnerPodTemplate: Runner pod image, labels, environment, scheduling.serviceAccountName: ServiceAccount the runner pod uses. Defaults to tf-runner.disableDriftDetection: Turns drift detection off, useful for heavy modules.storeReadablePlan: Stores the plan in a readable form, either json or human.refreshBeforeApply: Forces a state refresh before applying.force: Unconditionally re-plans and re-applies.tfstate: State lock handling, including automatic force unlock.
08. Practical scenarios
8.1 Plan first, approve by hand
The model most teams settle on for production. Leave approvePlan empty and the controller produces a plan and waits.
spec:
approvePlan: "" # empty means: plan, then wait
interval: 1m
path: ./
storeReadablePlan: human
sourceRef:
kind: GitRepository
name: helloworldOnce the plan is ready, a plan id appears on the resource. You approve by writing that id back into the field.
kubectl -n flux-system get tf/helloworld# take the plan id from the output and set it:
spec:
approvePlan: plan-main-b8e362c206KEY IDEA
The approval value is built from the branch and the commit hash, so approval is tied to a specific commit. If the code moves, the old approval no longer matches and a fresh plan is produced. That is what stops something you did not review from being applied.
8.2 Passing variables
Variables are either inline or read from a Secret or ConfigMap. Use the second one for anything sensitive.
spec:
vars:
- name: region
value: eu-central-1
- name: instance_count
value: "3"
varsFrom:
- kind: Secret
name: db-credentials
- kind: ConfigMap
name: cluster-settings
varsKeys:
- cluster_name
- environment8.3 Outputs as Kubernetes Secrets
This is one of the strongest features. A connection string or a resource name produced by Terraform becomes a Secret that workloads in the cluster can read. The manual copy and paste step between infrastructure and application disappears.
Get Eren Ozdemir’s stories in your inbox
Join Medium for free to get updates from this writer.
terraform side
output "bucket_name" {
value = aws_s3_bucket.this.id
}output "connection_string" {
value = azurerm_storage_account.this.primary_connection_string
sensitive = true
}controller side
spec:
approvePlan: auto
writeOutputsToSecret:
name: storage-outputs
outputs:
- bucket_name
- connection_string:conn # rename with old:new
labels:
owner: data-platformapplication side
env:
- name: BUCKET
valueFrom:
secretKeyRef:
name: storage-outputs
key: bucket_name8.4 Ordering with dependencies
You cannot put a database inside a network that does not exist yet. dependsOn solves exactly that: the dependent object does not start until the one it needs is ready.
apiVersion: infra.contrib.fluxcd.io/v1alpha2
kind: Terraform
metadata:
name: database
spec:
dependsOn:
- name: network
approvePlan: auto
path: ./database
varsFrom:
- kind: Secret
name: network-outputs # written by the network layerKEY IDEA
Combined with output writing, this gives you layered infrastructure. The network layer writes its outputs to a Secret and the database layer reads them as inputs. Two separate state files, one dependable chain.
8.5 Health checks
A successful apply does not prove the thing you built actually answers. Health checks close that gap.
spec:
healthChecks:
- name: postgres
type: tcp
address: "{{.outputs.db_host}}:5432"
timeout: 20s
- name: api
type: http
url: "https://{{.outputs.endpoint}}/healthz"
timeout: 10s8.6 Controlling drift detection
Drift detection is on by default. There are three positions you can take.
# 1) off entirely, for heavy modules with many resources
spec:
disableDriftDetection: true# 2) detect but do not correct
spec:
approvePlan: ""# 3) detect and correct automatically
spec:
approvePlan: auto
8.7 Deletion behaviour
By default, deleting the Terraform object does not delete what it built. If you want that, you have to say so.
spec:
destroyResourcesOnDeletion: true # handle with careWATCH OUT
With this on, deleting the object destroys real infrastructure. The controller builds a destroy plan from the parameters it currently holds, so those parameters have to be correct at the moment of deletion. In production it is safer to leave this off and make destruction a separate, deliberate action.
8.8 Cloud credentials
The runner pod has to get a cloud identity from somewhere. The worst option is a long lived key in a Secret. The best is the cloud provider’s own identity federation.
# simple: environment variables from a Secret
spec:
runnerPodTemplate:
spec:
envFrom:
- secretRef:
name: cloud-credentials# better: federated identity, IRSA on AWS or Workload Identity on Azure
spec:
serviceAccountName: tf-runner-with-cloud-identity
runnerPodTemplate:
metadata:
labels:
azure.workload.identity/use: "true"KEY IDEA
With federation the pod exchanges its Kubernetes identity for a short lived cloud token. Because no secret is stored, there is nothing to expire, nothing to rotate and nothing to leak. It takes more setup and it is the right answer for production.
8.9 Multi-tenancy
If several teams share a cluster, each should run in its own namespace under its own ServiceAccount. The controller supports this directly.
# Helm values: which namespaces may run runners
runner:
allowedNamespaces:
- team-data
- team-platform# on the resource: which identity it runs as
metadata:
namespace: team-data
spec:
serviceAccountName: team-data-runnerThis is soft isolation. Teams cannot see each other’s resources, but they share a controller and the same nodes. If you need a hard boundary, you need separate clusters.
8.10 Customising the runner image
The default runner image carries OpenTofu and very little else. If you need extra tooling you can build your own, and the project ships a Dockerfile to start from.
# per resource
spec:
runnerPodTemplate:
spec:
image: registry.example.com/custom-tf-runner:v1.2.0# or globally, through the RUNNER_POD_IMAGE variable on the controller09. Design patterns
Installing the controller is the easy part. The real decision is how requests reach it. Three patterns cover most of what people build.
A. Repository driven, pure GitOps
Every request is a file change. Someone opens a branch, writes the manifest, a pull request is reviewed and merged, and the controller does the rest.
- Strength: git is the single source of truth. Every change has an author, a reviewer and a way back.
- Weakness: users need to know git and HCL, and validation only runs at apply time.
- Best for: platform teams whose users are engineers.
B. API or portal driven
The user fills in a form. An application validates the request and writes the Terraform object into Kubernetes on their behalf.
- Strength: the user needs no Terraform knowledge, and validation runs before submission, so name clashes and quota problems are caught early.
- Weakness: git is no longer the single source of truth. What exists lives in the application’s database.
- Best for: self-service platforms whose users are not engineers.
C. Hybrid: code in git, inputs through an API
The balanced option, and the one most self-service platforms land on. Modules stay in the repository, versioned and reviewed. Only the inputs are dynamic, delivered through a ConfigMap or Secret.
- Infrastructure logic stays somewhere it can be reviewed.
- The user still sees a simple form.
- Because only inputs change at request time, changes to the code itself remain under normal review.
Barrier for users
A · Repo driven: High
B · API driven: Low
C · Hybrid: Low
Audit trail
A · Repo driven: Git history
B · API driven: Application records
C · Hybrid: Both
Validation timing
A · Repo driven: At apply
B · API driven: Before submit
C · Hybrid: Before submit
Build cost
A · Repo driven: Low
B · API driven: High
C · Hybrid: Medium
Source of truth
A · Repo driven: Git
B · API driven: The application
C · Hybrid: Code in git, state in the app
KEY IDEA
GitOps is not all or nothing. You can decide what belongs in git. Keep the logic there and let the inputs be dynamic.
10. A worked example
To make pattern C concrete, here is how it looks in a real self-service platform on Azure. Users are data scientists and analysts, so a form was the only realistic interface.
- The user fills in a form in a web application, choosing a resource and naming it.
- The application validates before anything is submitted: schema, global name availability, and whether the target subnet still has addresses free for a private endpoint.
- The request goes to an approver. Approval is a business rule in the application, not a git reviewer.
- On approval the application writes two objects: a ConfigMap holding the inputs as JSON, and a Terraform resource pointing at the shared module catalogue in git.
- The controller starts a runner pod, which pulls the modules from the GitRepository and mounts the ConfigMap as a variables file.
- Status flows back through the Terraform resource and the portal shows the user where their request is.
the resource the portal writes
spec:
approvePlan: auto
path: ./terraform/catalog # shared modules, reviewed in git
sourceRef:
kind: GitRepository
name: platform-modules
storeReadablePlan: json # so the portal can show the plan
backendConfig: ... # one state key per deployment
vars:
- name: inputs_file
value: /tfvars/parameters.json # written by the portal as a ConfigMap
runnerPodTemplate:
spec:
volumes:
- name: tfvars
configMap:
name: request-8f21c4FROM THE FIELD
The point of this shape is that no user ever writes Terraform, yet every module they use has been through code review. One state key per deployment means one request never blocks another. And because the plan is stored in a readable form, the portal can show a person exactly what is about to change before anyone approves it.
11. Where it fits
- Self-service infrastructure platform: Approval, isolation and repeatability are already part of the tool
- Shared cluster with several teams: Soft isolation through namespaces and service accounts
- Bridging Kubernetes and cloud resources: Terraform outputs become Secrets that workloads read directly
- Regulated or audited environments: Plan approval, drift detection and a durable record
- Teams with existing Terraform: Runs your modules as they are, no rewrite
- Ephemeral environments: Tie the lifetime of infrastructure to the lifetime of an object
- Gradual GitOps adoption: Start with drift detection only and move towards automation
12. When not to use it
- You do not already run Kubernetes. Standing up and operating a cluster for this alone costs more than it returns.
- Your team is happy with its pipelines. The gain is marginal and you take on a new operational surface.
- The infrastructure is built once and rarely changes. Continuous reconciliation has nothing to do.
- You need hard isolation. Runner pods share a cluster, which is a soft boundary.
- Your network is heavily restricted. Provider downloads, image pulls and gRPC all need planning up front.
13. How it compares
Tofu Controller
Approach: Runs your existing Terraform inside Kubernetes
Better when: You have Terraform investment and already run Kubernetes
Crossplane
Approach: You define your own API types as Kubernetes objects
Better when: You are Kubernetes native and want a clean abstraction for developers
Atlantis
Approach: Plan and apply driven from pull requests
Better when: You want the whole workflow to stay on the pull request
Spacelift, env0 and similar
Approach: Managed SaaS platform
Better when: You would rather outsource the operational load
A plain CI/CD pipeline
Approach: Terraform as a job
Better when: Simple needs and small teams
The Crossplane comparison comes up most often. They are not really competitors, they answer different questions. Crossplane asks you to model your infrastructure again and rewards you with a very clean interface for developers. Tofu Controller takes the modules you already have and brings the whole Terraform provider ecosystem with them. Plenty of teams run both: foundational infrastructure that rarely changes in Terraform, developer facing services in Crossplane.
14. What to know before production
None of the following is prominent in the documentation, and all of it turns up eventually.
The controller and the runner move together
The runner pod speaks gRPC to the controller and the two are released as a pair. There is no such thing as upgrading only the Terraform version. Needing a newer provider can turn into a full controller upgrade, so plan for that.
The move to OpenTofu is one way
From v0.16.0 the engine is OpenTofu. State written by OpenTofu cannot be read back by Terraform. If you are migrating an existing environment this needs a real plan, it does not happen by itself.
Provider resolution in restricted networks
OpenTofu resolves providers from its own registry by default, and corporate firewalls often block it. The fix is to spell the provider source in full, or to run a mirror.
terraform {
required_providers {
azurerm = {
source = "registry.terraform.io/hashicorp/azurerm"
}
}
}WATCH OUT
The trap here is that every module needs its own declaration. Setting it in the root is not enough. A submodule without one falls back to inference from the default registry and goes straight back to the blocked host. The result is a failure that only appears for certain modules, which makes it unpleasant to diagnose.
Image reachability
The same network restriction often covers image registries. Copying the controller and runner images into your own registry keeps the pull inside your network.
The runner image is minimal
There are no shell tools in the default runner image. If your design depends on local-exec, that door is closed. The constraint is arguably a good one because it pushes everything through providers, but it shapes your design and it is expensive to discover late.
Choosing a state backend
The Kubernetes Secret backend is convenient for trying things out and wrong for production. It has size limits, keeps no version history, and disappears with the cluster. Use S3, Azure Blob or GCS, and give each resource its own state key so one run never blocks another.
Secret handling
Keeping cloud credentials in a Kubernetes Secret is the default path, but base64 is not encryption. Anyone who can read secrets in that namespace can read them. Use federation wherever you can. Where you cannot, narrow who can read secrets and put rotation on a schedule.
15. Checklist and resources
Before you go live
- Is Flux v2 installed and healthy?
- Are ports 30000 and 80 open, and are the provider registry and image registry reachable?
- Have you chosen a state backend, with one key per resource?
- Is the cloud identity federated, or is there a stored secret to look after?
- Is approvePlan empty in production, so plans go to a human?
- Was destroyResourcesOnDeletion set deliberately?
- Does each team have its own namespace and service account?
- Are outputs written to Secrets, and does the consuming side know about them?
- Does your upgrade plan cover the controller and the runner together?
Resources
- Project repository: https://github.com/flux-iac/tofu-controller
- Documentation: https://flux-iac.github.io/tofu-controller/
- Getting started: https://flux-iac.github.io/tofu-controller/getting_started/
- Flux: https://fluxcd.io/
- OpenTofu: https://opentofu.org/
If you are building something similar, or you have tried one of these patterns, I would be glad to hear how it went.









