Kubernetes Operator Pythonic Framework (Kopf)

1.44.5 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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

view raw JSON →