Operators & CRDs
Kubernetes ships with Pods, Deployments and Services, but its real power is that you can teach it new kinds of objects. A CustomResourceDefinition (CRD) adds a new resource type to the API, and an operator is a controller that reconciles objects of that type, encoding the knowledge a human operator would have ("how to fail over this database", "how to renew this certificate").
Examples you'll meet in real clusters:
| Operator | Custom resources | Automates |
|---|---|---|
| cert-manager | Certificate, Issuer |
Obtaining and renewing TLS certificates |
| CloudNativePG | Cluster, Backup |
PostgreSQL replication, failover, backups |
| Prometheus Operator | Prometheus, ServiceMonitor, PrometheusRule |
Monitoring configuration |
| Strimzi | Kafka, KafkaTopic |
Kafka clusters |
| Argo CD | Application |
GitOps deployments |
Defining a CRD
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: websites.demo.example.com # <plural>.<group>
spec:
group: demo.example.com
scope: Namespaced
names:
kind: Website
plural: websites
singular: website
shortNames: [ws]
versions:
- name: v1
served: true
storage: true
subresources:
status: {}
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [domain, replicas]
properties:
domain: {type: string}
replicas: {type: integer, minimum: 1, maximum: 10}
gitRepo: {type: string}After kubectl apply, the API server serves the new type like any other:
apiVersion: demo.example.com/v1
kind: Website
metadata:
name: blog
spec:
domain: blog.example.com
replicas: 2
gitRepo: https://github.com/acme/blogkubectl get websites # or: kubectl get ws
kubectl describe website blog
kubectl explain website.specThe API server validates custom resources against the schema. A model of that check for the Website schema:
import yaml
schema = yaml.safe_load("""
type: object
required: [domain, replicas]
properties:
domain: {type: string}
replicas: {type: integer, minimum: 1, maximum: 10}
gitRepo: {type: string}
""")
TYPES = {"string": str, "integer": int, "object": dict}
def validate(spec, schema, path="spec"):
errors = []
for field in schema.get("required", []):
if field not in spec:
errors.append(f'{path}.{field}: Required value')
for field, value in spec.items():
rule = schema["properties"].get(field)
if rule is None:
errors.append(f'{path}.{field}: unknown field (pruned)')
continue
if not isinstance(value, TYPES[rule["type"]]) or isinstance(value, bool):
errors.append(f'{path}.{field}: Invalid value: must be of type {rule["type"]}')
elif "minimum" in rule and value < rule["minimum"]:
errors.append(f'{path}.{field}: Invalid value: {value}: should be greater than or equal to {rule["minimum"]}')
elif "maximum" in rule and value > rule["maximum"]:
errors.append(f'{path}.{field}: Invalid value: {value}: should be less than or equal to {rule["maximum"]}')
return errors or ["valid"]
for name, spec in {
"blog": {"domain": "blog.example.com", "replicas": 2},
"huge": {"domain": "shop.example.com", "replicas": 50},
"typo": {"domian": "docs.example.com", "replicas": "3"},
}.items():
print(name, "->", "; ".join(validate(spec, schema)))blog -> valid
huge -> spec.replicas: Invalid value: 50: should be less than or equal to 10
typo -> spec.domain: Required value; spec.domian: unknown field (pruned); spec.replicas: Invalid value: must be of type integer
Writing the controller
The operator watches Website objects and makes sure the right Deployment, Service and Ingress exist for each one, then writes back status. The core is the same reconcile loop you saw for ReplicaSets, made idempotent: it computes the desired children from the spec and creates, updates or deletes to match, so running it twice changes nothing.
cluster = {} # (kind, name) -> object, stands in for the API
def desired_children(site):
name, spec = site["name"], site["spec"]
return {
("Deployment", name): {"replicas": spec["replicas"], "image": "nginx:1.27"},
("Service", name): {"port": 80},
("Ingress", name): {"host": spec["domain"]},
}
def reconcile(site):
actions = []
want = desired_children(site)
for key, body in want.items():
if key not in cluster:
actions.append(f"create {key[0]}/{key[1]}")
elif cluster[key] != body:
actions.append(f"update {key[0]}/{key[1]} {cluster[key]} -> {body}")
cluster[key] = body
for key in [k for k in cluster if k[1] == site["name"] and k not in want]:
actions.append(f"delete {key[0]}/{key[1]}")
del cluster[key]
site["status"] = {"readyReplicas": site["spec"]["replicas"], "url": f"https://{site['spec']['domain']}"}
return actions or ["in sync, nothing to do"]
blog = {"name": "blog", "spec": {"domain": "blog.example.com", "replicas": 2}}
print("1st reconcile:", reconcile(blog))
print("2nd reconcile:", reconcile(blog))
blog["spec"]["replicas"] = 4
print("after edit: ", reconcile(blog))
print("status:", blog["status"])1st reconcile: ['create Deployment/blog', 'create Service/blog', 'create Ingress/blog']
2nd reconcile: ['in sync, nothing to do']
after edit: ["update Deployment/blog {'replicas': 2, 'image': 'nginx:1.27'} -> {'replicas': 4, 'image': 'nginx:1.27'}"]
status: {'readyReplicas': 4, 'url': 'https://blog.example.com'}
Real operators are written with frameworks such as Kubebuilder / Operator SDK (Go), kopf (Python) or java-operator-sdk. They add owner references (so deleting the Website garbage-collects its children), finalizers (to clean up external resources such as DNS records before deletion), and retry with back-off on errors.
# The same idea with kopf (Python), for a real cluster:
import kopf
@kopf.on.create("demo.example.com", "v1", "websites")
@kopf.on.update("demo.example.com", "v1", "websites")
def reconcile(spec, name, namespace, **_):
... # create/patch the Deployment, Service and Ingress with the Kubernetes client
return {"url": f"https://{spec['domain']}"}Levels of operator maturity
The Operator Framework describes five capability levels: (1) basic install, (2) seamless upgrades, (3) full lifecycle (backups, failure recovery), (4) deep insights (metrics, alerts), (5) auto pilot (auto-scaling, auto-tuning). When choosing an operator for a database, look for level 3 or higher.
Tip: Don't write an operator when a Helm chart would do. Operators shine when ongoing operational actions (failover, backup, upgrade orchestration) must happen automatically.
Test yourself
What does a CustomResourceDefinition do?
- Runs a container
- Adds a new resource type to the Kubernetes API
- Defines a Docker image
- Creates a namespace
What makes a controller's reconcile function safe to run repeatedly?
- Running it only once
- Idempotency: it converges to the desired state and does nothing when already there
- Using random names
- Deleting everything first
Which of these is a typical job for an operator rather than a Helm chart?
- Rendering YAML
- Automatically failing over a database primary
- Setting an image tag
- Creating a namespace