Registry / devops / kopf
library1.44.6pypypi✓ verified 23d ago

Kopf (Kubernetes Operator Pythonic Framework) is a Python framework designed to simplify the development of Kubernetes operators. It enables developers to write event-driven or state-driven handler functions with minimal boilerplate, focusing on domain logic rather than Kubernetes API infrastructure. The library is production-ready and stable (semantic v1), with current version 1.44.5, and receives regular maintenance for new Python and Kubernetes versions, without active development of new major functionality or imminent breaking changes.

pip install kopf
INSTALL
IMPORT
SIG · KOPF
K
kopf
devopspythonv1.44.6
Install
5.8s avg
Import
1513ms
Disk
43MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.44.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 1.597s · 35.5MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 5.8s · import 1.429s · 38MB
43MB installed
● package 43MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

kopf
import kopf
The primary import for accessing all Kopf functionalities, including decorators and settings.

This quickstart demonstrates a basic Kopf operator that watches for 'kopfexamples' custom resources. It includes handlers for creation, update, and deletion events, logging relevant information and returning status updates. The code is meant to be saved as a Python file (e.g., `your_operator_file.py`) and run using the `kopf run` CLI command after applying the necessary CRD.

import kopf import os @kopf.on.create('kopfexamples') def create_fn(spec, name, logger, **kwargs): message = f"Hello from Kopf! Created {name} with spec: {spec}" logger.info(message) return {'message': message} @kopf.on.update('kopfexamples') def update_fn(old, new, diff, name, logger, **kwargs): logger.info(f"Updated {name} with changes: {diff}") return {'message': f"Updated {name} with changes."} @kopf.on.delete('kopfexamples') def delete_fn(name, logger, **kwargs): logger.info(f"Deleted {name}. Goodbye!") return {'message': f"Deleted {name}."} # To run this operator: # 1. Apply the kopfexamples CRD: kubectl apply -f https://github.com/nolar/kopf/raw/main/examples/crd.yaml # 2. Run the operator: kopf run your_operator_file.py --verbose # 3. Create a custom resource: kubectl apply -f - <<EOF # apiVersion: kopf.dev/v1 # kind: KopfExample # metadata: # name: my-example # spec: # field: value # EOF
kopf --version
Debug
Known issues
breakingKubernetes versions 1.16 and later introduce strict structural schemas that prune unknown fields in custom resources. If Kopf's status storage is not configured to use annotations, any status fields written by Kopf might be silently lost unless `x-kubernetes-preserve-unknown-fields: true` is explicitly added to your Custom Resource Definition (CRD) schema.
fix
For custom resources, add `x-kubernetes-preserve-unknown-fields: true` to your CRD schema. Alternatively, configure Kopf to use `AnnotationsDiffBaseStorage` for persistence (`settings.persistence.diffbase_storage = kopf.AnnotationsDiffBaseStorage(...)`).
affects: All versions when running on Kubernetes >= 1.16 without proper CRD configuration.
gotchaPrior to Kopf version 1.44.0, operators could experience connection freezes or silent disconnections when running behind load balancers in Kubernetes clusters, especially during periods of inactivity. This was due to load balancers closing idle connections while the operator remained unaware.
fix
Upgrade Kopf to version 1.44.0 or newer. This version introduced the use of bookmark events to maintain connection liveness and prevent such freezes.
affects: <1.44.0
gotchaRunning multiple instances of a Kopf operator for the same resource kind without proper peering configuration can lead to double-processing of events and inconsistent states.
fix
Kopf includes a 'peering' mechanism to coordinate multiple operator instances. Ensure your deployment is configured to leverage Kopf's peering capabilities, which can be done automatically or configured manually via the `peering.yaml` resource. In development, the `kopf run` command can temporarily suppress deployed instances.
affects: All versions
gotchaWhen developing admission webhooks or using features like self-signed certificates and Ngrok tunnels for local development, the `kopf[dev]` extra package is required. Without it, Kopf will raise startup errors if these functionalities are attempted.
fix
Install Kopf with the `dev` extra: `pip install 'kopf[dev]'`. This ensures that necessary development-only dependencies (e.g., for SSL cryptography and certificate generation) are available.
affects: All versions
Errors
Common errors & fixes
kopf._cogs.clients.errors.APIForbiddenError: ('exchangerates.operators.brennerm.github.io is forbidden: User "system:serviceaccount:default:exchangerates-operator" cannot list resource "exchangerates" in API group "operators.brennerm.github.io" at the cluster scope', {'kind': ...})
The Kubernetes ServiceAccount running the Kopf operator lacks the necessary RBAC permissions (ClusterRole/Role and ClusterRoleBinding/RoleBinding) to perform operations on the specified Kubernetes resources.
fix
Grant the appropriate ClusterRole or Role with verbs like `list`, `watch`, `patch` on the affected API group and resources to the ServiceAccount, and ensure the ClusterRoleBinding or RoleBinding correctly links them.
kubectl freezes on object deletion
Kopf operators add finalizers to custom resources. If the operator is down or unresponsive, it cannot remove these finalizers, causing Kubernetes to block the deletion of the object indefinitely.
fix
Restart the Kopf operator to allow it to process the deletion event and remove the finalizers. If the operator cannot be restarted, manually remove the finalizers from the resource using `kubectl patch <kind> <name> -p '{"metadata": {"finalizers": []}}' --type merge`.
ModuleNotFoundError: No module named 'MyMod' (when running with `kopf run`)
When `kopf run` executes, it might not correctly resolve the Python module path for local modules or packages that are not part of the standard library or directly in the operator's main script directory.
fix
Ensure the module is discoverable by Python by running `kopf run` from the appropriate working directory where the module is accessible, or by setting the `PYTHONPATH` environment variable to include the module's parent directory, or by installing the local package in editable mode (`pip install -e .`).
Ran out of valid credentials
The Kubernetes service account token used by the Kopf operator has expired, and the operator failed to re-authenticate or refresh its credentials, leading to a loss of API access.
fix
Ensure the operator's environment and Kubernetes cluster configuration allow for automatic token refresh. Consider updating Kopf to a newer version as improvements in authentication handling have been made, and verify network connectivity to the Kubernetes API server.
KeyError: 'some_field' (in handler functions for `spec` or `body`)
A handler function attempted to access a field within the `spec`, `status`, or `body` of a Kubernetes resource that does not exist or is unexpectedly missing.
fix
Access potentially missing fields using dictionary's `get()` method (e.g., `spec.get('some_field')` or `body.get('some_field', default_value)`) to provide a default or handle its absence gracefully, or explicitly check for the field's existence (e.g., `if 'some_field' in spec:`) before accessing it.
Upgrade
Version history
1.44.6latest on PyPI · released Jun 3, 2026
Audit
Dependencies
pythonrequiredRequired runtime environment.
kubernetesoptionalOften used for direct Kubernetes API interaction within operator handlers.
Agent activity
19 hits · last 30 days
node
16
OpenAI (training)
1
Resources
kopf — pip install kopf · libregistry