Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example that uses kopf + kr8s #243

Merged
merged 1 commit into from
Dec 12, 2023

Conversation

jacobtomlinson
Copy link
Member

Closes #235

Added an example that shows how to write an operator controller with kopf and kr8s together.

# controller.py
import re

import kopf
import kr8s
from kr8s.objects import Pod


@kopf.on.resume("pods")
@kopf.on.create("pods")
def add_os_labels(body, logger, **kwargs):
    pod = Pod(body)

    # Pod was deleted while trying to add OS labels, give up
    if not pod.exists():
        return

    # Pod already has OS labels, skip
    if "os-release/id" in pod.labels:
        return

    # Pod is not ready yet, retry in a bit
    if not pod.ready():
        raise kopf.TemporaryError(f"Pod {pod.name} is not ready yet", delay=10)

    # Get OS info
    try:
        output = pod.exec(["cat", "/etc/os-release"])
        os_info = output.stdout.decode()
    except kr8s.ExecError:
        logger.error(
            f"Failed to exec in pod {pod.name}, "
            "either cat is not included in the image or /etc/os-release is missing."
        )
        pod.label({"os-release/id": "unknown"})
        return

    # Clean OS labels
    labels = {}
    for label in os_info.splitlines():
        key, value = label.split("=")
        key = f"os-release/{key.lower().replace('_', '-')}"
        # Kubernetes only accepts label values with alphanumeric characters,
        # dots, dashes and underscores and a maximum length of 63 characters.
        value = re.sub("[^0-9a-zA-Z_.-]+", "", value)[:63]
        labels[key] = value

    # Apply OS labels
    pod.label(labels)

@github-actions github-actions bot added the documentation Improvements or additions to documentation label Dec 12, 2023
Copy link

codecov bot commented Dec 12, 2023

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (985a2a3) 94.55% compared to head (cf2b950) 94.55%.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #243   +/-   ##
=======================================
  Coverage   94.55%   94.55%           
=======================================
  Files          27       27           
  Lines        2701     2701           
=======================================
  Hits         2554     2554           
  Misses        147      147           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@jacobtomlinson jacobtomlinson merged commit 70b5e78 into kr8s-org:main Dec 12, 2023
9 checks passed
@jacobtomlinson jacobtomlinson deleted the kopf-example branch December 12, 2023 12:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Create kr8s + kopf documentation examples
1 participant