Create a Kubernetes Operator in Python

Overview

Kubernetes Operator is a convenient feature that allows you to automate and extend Kubernetes functionality through Custom Resources. The main language used to create Operators is go, but it's not limited to go. In this article, I will introduce a framework for creating an Operator in Python and how to use it easily.

What is a kubernetes operator?

Kubernetes Operator is an extension that automatically deploys applications such as DB and web server according to the definition of custom resources created by yourself. In addition to creating a normal container, you can automate according to your own code, so instead of just using the default function of Kubernetes, we went one step further, such as linking with an external cloud service or a database outside Kubernetes. You can achieve automation. Frameworks for creating Operators include operator-framework, which are often created in the go language.

See also: kubernetes official documentation (https://kubernetes.io/en/docs/concepts/extend-kubernetes/operator/)

About kopf

kopf (Kubernetes Operator Pythonic Framework) is a framework for creating Kubernetes Operators in Pyhon. Simply add a decorator to the code you want to automate, and you can execute your code as Kubernetes resources change.

See also: https://github.com/nolar/kopf

Installation method

Implementation environment:

You can install it from pip.

pip install kopf

How to use

It's easy to run, just specify the Operator code you want to run with the kopf command introduced during installation.

kopf run your_code.py --verbose

TIPS:

Sample code

There are a lot of sample code on github, so basically you can understand the function by looking at it. I would like to explain by quoting a part of the sample code below.

Responds to resource creation

kopf/examples/01-minimal/example.py


import kopf


@kopf.on.create('zalando.org', 'v1', 'kopfexamples')
def create_fn(spec, **kwargs):
    print(f"And here we are! Creating: {spec}")
    return {'message': 'hello world'}  # will be the new status

In kopf, you can add a decorator to a function to execute code as the kubernetes resources change. This sample code prints the resource definition to standard output when the kopfexamples resource is created. In addition, the return value is saved in the status of the created resource, and you can check the contents with the kubectl describe command.

Creating a child resource

kopf/examples/02-children/example.py


import kopf
import pykube
import yaml


@kopf.on.create('zalando.org', 'v1', 'kopfexamples')
def create_fn(spec, **kwargs):

    # Render the pod yaml with some spec fields used in the template.
    doc = yaml.safe_load(f"""
        apiVersion: v1
        kind: Pod
        spec:
          containers:
          - name: the-only-one
            image: busybox
            command: ["sh", "-x", "-c"]
            args: 
            - |
              echo "FIELD=$FIELD"
              sleep {spec.get('duration', 0)}
            env:
            - name: FIELD
              value: {spec.get('field', 'default-value')}
    """)

    # Make it our child: assign the namespace, name, labels, owner references, etc.
    kopf.adopt(doc)

    # Actually create an object by requesting the Kubernetes API.
    api = pykube.HTTPClient(pykube.KubeConfig.from_env())
    pod = pykube.Pod(api, doc)
    pod.create()
    api.session.close()

    # Update the parent's status.
    return {'children': [pod.metadata['uid']]}

When creating a resource, a new pod with a definition according to the resource content is created. The point is kopf.adopt (doc), and when you do this, the information of the triggered resource will be recorded in the ownerReferences field of the created pod. By having this information, a parent-child relationship is formed between the triggered resource and the created pod, and when the parent resource is deleted, the child pod will be deleted at the same time.

Summary

I introduced how to create an Operator for kubernetes in Python using the kopf framework. If you haven't touched go but Python, why not take this opportunity to create an Operator for Kubernetes?

Recommended Posts

Create a Kubernetes Operator in Python
Create a function in Python
Create a dictionary in Python
Create a binary file in Python
Create a random string in Python
Create a simple GUI app in Python
Create a JSON object mapper in Python
[GPS] Create a kml file in Python
Create a Python module
Create SpatiaLite in Python
Create a Python environment
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
I want to create a window in Python
Create a standard normal distribution graph in Python
How to create a JSON file in Python
Create a virtual environment with conda in Python
Create a simple momentum investment model in Python
Create a new page in confluence with Python
Create a datetime object from a string in Python (Python 3.3)
Create a package containing global commands in Python
Create a MIDI file in Python using pretty_midi
Create a loop antenna pattern in Python in KiCad
[Docker] Create a jupyterLab (python) environment in 3 minutes!
Take a screenshot in Python
Create a Wox plugin (Python)
Make a bookmarklet in Python
Create a python numpy array
Draw a heart in Python
Create a directory with python
Create a data collection bot in Python using Selenium
[LINE Messaging API] Create a rich menu in Python
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
In Python, create a decorator that dynamically accepts arguments Create a decorator
Create a fake Minecraft server in Python with Quarry
How to create a kubernetes pod from python code
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
[python] Manage functions in a list
Hit a command in Python (Windows)
Create a CSV reader in Flask
Create a local scope in Python without polluting the namespace
Create a list in Python with all followers on twitter
Create a python GUI using tkinter
Create a Python environment on Mac (2017/4)
Draw a scatterplot matrix in python
Create a child account for connect with Stripe in Python
Let's create a script that registers with Ideone.com in Python.
ABC166 in Python A ~ C problem
Create a virtual environment with Python!
Write A * (A-star) algorithm in Python
Create Gmail in Python without API
Solve ABC036 A ~ C in Python
Create a python environment on centos
Create code that outputs "A and pretending B" in python
Write a vim plugin in Python
Create Python project documentation in Sphinx
Write a depth-first search in Python
Create a tool to check scraping rules (robots.txt) in Python
Implementing a simple algorithm in Python 2