Skip to main content

3 posts tagged with "python"

View All Tags

An asynchronous Kubernetes client for Python

· 2 min read

The problem​

Running the same kubectl command against many clusters in a sequential loop takes a long time. For example:

for ctx in $(kubectl config view | yq '.contexts.[].name');
do echo $ctx;
kubectl --context $ctx get cm aws-auth -n kube-system -o yaml | yq e '.data.mapUsers' - | yq -;
done

The solution​

Use an asynchronous Kubernetes client in Python:

pip3 install kubernetes_asyncio

Let's define a class that launches the tasks and waits for them to finish:

import asyncio
from kubernetes_asyncio import client, config
from kubernetes_asyncio.client.api_client import ApiClient

import typing as t


class k8sAsyncTask:
def __init__(self, contexts: list, task: t.Callable):
self._ctxs = contexts
self._task = task

async def _task_runner(self, ctx):
try:
# Load the cluster configuration
await config.load_kube_config(context=ctx)

# use the context manager to close http sessions automatically
async with ApiClient() as api:
result = await self._task(api)
return ctx, result

except Exception as e:
# Handle errors as needed
print(f"Error in cluster {ctx}: {str(e)}")
return ctx, None

async def tasks_results(self):
tasks = []

for ctx in self._ctxs:
task = asyncio.create_task(self._task_runner(ctx))
tasks.append(task)

# Wait for all tasks to finish
completed_tasks = await asyncio.gather(*tasks)
# Turn the lists of results into dictionaries
zipped = dict(zip(self._ctxs, completed_tasks))
result = {k: zipped[k][1] for k in zipped}

return result

Define a task that reads the ConfigMap containing the AWS users:

import yaml


async def k8s_get_aws_auth(api):
v1 = client.CoreV1Api(api)
result = await v1.read_namespaced_config_map(name="aws-auth", namespace="kube-system")
users = yaml.safe_load(result.data["mapUsers"])
users_groups = [{"username": user["username"], "group": user["groups"]} for user in users]
return users_groups

Start the tasks and wait for the results:

CLUSTERS = ["dev", "prod"]


async def main():
k = k8sAsyncTask(CLUSTERS, k8s_get_aws_auth)
r = await k.tasks_results()
return r


if __name__ == "__main__":
r = asyncio.run(main())
print(r)

Done

Takeaway​

  • With many clusters, running ad hoc tasks concurrently can save time.

xonsh - python-powered shell

· 5 min read

img

Why? That's a recipe for a debate. In my case, xonsh helped me finish a tedious task at work faster than I could in Bash or Python alone.

Is that a good idea? Probably not as a general rule. AWS, for example, writes its EC2 bootstrap script in Bash, though I find it hard to read. For one-off jobs I think xonsh can be useful. I'd be careful about putting those scripts in Git or CI and leaving colleagues to debug them.

Example 1: a CLI to restart Kubernetes workloads​

#!/usr/bin/env xonsh
# PYTHON_ARGCOMPLETE_OK
import argparse
import argcomplete
from argcomplete.completers import ChoicesCompleter

import json
import yaml
import os

# save all kubernetes contextes
with open(os.environ["KUBECONFIG"]) as y: contexts = tuple([ctx["name"] for ctx in yaml.safe_load(y)["contexts"]])
# WARNING: terminal freezes during autocompletion of something like bellow
# contexts = $(kubectl config view | yq e '.contexts[].name' - | sort).strip().split)('\n')

example_text = "Example: xonsh restart-pods.xsh --context sandbox"
parser = argparse.ArgumentParser(description="Restart Argo CD workloads", epilog=example_text)
parser.add_argument('--context', required=True, help="Kubernetes contexts").completer=ChoicesCompleter((contexts))
parser.add_argument('-n', '--namespace', help="argocd namespace", default="argocd")
argcomplete.autocomplete(parser)
args = parser.parse_args()

k_all: str = $(kubectl --context @(args.context) -n @(args.namespace) get all --output json)
k_all: dict = json.loads(k_all)["items"]

for obj in k_all:
if obj["kind"] in ["Deployment", "StatefulSet"]:
kubectl --context @(args.context) --namespace @(args.namespace) \
rollout restart @(obj["kind"].lower()) @(obj["metadata"]["name"]) -o name

Run the script:

$ xonsh restart-cli.xsh --context sandbox
deployment.apps/argocd-applicationset-controller
deployment.apps/argocd-image-updater
deployment.apps/argocd-notifications-controller
deployment.apps/argocd-redis
deployment.apps/argocd-repo-server
deployment.apps/argocd-server
statefulset.apps/argocd-application-controller

Example 2: an API to restart Kubernetes workloads​

import uvicorn
from fastapi import FastAPI

import typing as t
import json

app = FastAPI()


@app.get("/restart-pods/{context}")
async def restart_pods(context: str, namespace: str = "argocd"):
"""
Restart Deployments and StatefulSets in the selected namespace using `kubectl rollout restart`.
"""
k_all: str = $(kubectl --context @(context) -n @(namespace) get all --output json)
k_all: dict = json.loads(k_all)["items"]

result = list()

for obj in k_all:
if obj["kind"] in ["Deployment", "StatefulSet"]:
restarted = $(kubectl --context @(context) --namespace @(namespace) \
rollout restart @(obj["kind"].lower()) @(obj["metadata"]["name"]) -o name).strip()
result.append(restarted)
return result


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
# Start Uvicorn
xonsh api.xsh
INFO: Started server process [9467]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
# A successful request returns a response like this
INFO: 127.0.0.1:64893 - "GET /restart-pods/sandbox?namespace=argocd HTTP/1.1" 200 OK

# Send the request from another terminal
curl -X 'GET' \
'http://127.0.0.1:8000/restart-pods/sandbox?namespace=argocd' \
-H 'accept: application/json' | jq
[
"deployment.apps/argocd-applicationset-controller",
"deployment.apps/argocd-image-updater",
"deployment.apps/argocd-notifications-controller",
"deployment.apps/argocd-redis",
"deployment.apps/argocd-repo-server",
"deployment.apps/argocd-server",
"statefulset.apps/argocd-application-controller"
]

Example 3: Typer CLI with xonsh​

I wanted to see how quickly I could write and share scripts with xonsh, as an alternative to Warp workflows or Taskfile.

Let's recreate this workflow:

warp​

---

name: Terminate AWS EC2 by k8s Node name
command: |
ec2_id=$(kubectl --context {{ctx}} get nodes {{node}} \
-o jsonpath="{.spec.providerID}" \
| /usr/bin/grep -Eo "i-\w*")

echo "DEBUG: <node-name={{node}}>,<ec2_id=${ec2_id}>"

aws ec2 terminate-instances \
--profile {{awsProfile}} \
--region {{awsRegion}} \
--instance-ids ${ec2_id} \
| jq

tags:
- aws
- kubernetes
- k8s
- karma
description: Terminate AWS EC2 by k8s Node name
arguments:
- name: ctx
description: kubernetes context
default_value: ~
- name: node
description: kubernetes Node
default_value: ~
- name: awsProfile
description: aws named profile
default_value: ~
...

xsh​

def k8s_node_aws_instance_id(context: str, node: str):
"""
The input is the Kubernetes node name ip-10-51-38-27.eu-west-1.compute.internal
We need to find the AWS instance ID
The API returns a provider ID of aws:///eu-west-1b/i-086fd4feb458ecde3
Result: i-086fd4feb458ecde3
"""
provider_id = !(kubectl --context @(context) get node @(node) -o jsonpath="{.spec.providerID}")
provider_id = str(provider_id)
logging.debug(f"providerID {provider_id}")
ec2_id = provider_id.split('/')[-1].replace('"', '')
return ec2_id

# TODO: encapsulate arguments
@app.command(help=":ship: Terminate a node")
def k8s_terminate_node(
node: str = typer.Argument(None, help="kubernetes Node name"),
context: str = typer.Option(None, "--context", "-ctx", help="kubernetes context"),
profile: str = typer.Option("default", "--profile", "-p", help="aws named profile"),
region: str = typer.Option("eu-west-1", "--region", "-r", help="aws region"),
):
# Look up the node's instance ID
ec2_id = k8s_node_aws_instance_id(context, node)
print(f"node {node}, aws ec2 instance_id {ec2_id}")

# Drain the node and shut it down
kubectl --context @(context) drain @(node) --delete-local-data --ignore-daemonsets --force
aws ec2 terminate-instances --profile @(profile) --region eu-west-1 --instance-ids @(ec2_id) | jq


@app.command(help=":ship: Connect to a node")
def k8s_ssm_node(
node: str = typer.Argument(None, help="kubernetes Node name"),
context: str = typer.Option(None, "--context", "-ctx", help="kubernetes context"),
profile: str = typer.Option("default", "--profile", "-p", help="aws named profile"),
region: str = typer.Option("eu-west-1", "--region", "-r", help="aws region"),
):
# Look up the node's instance ID
ec2_id = k8s_node_aws_instance_id(context, node)
print(f"node {node}, aws ec2 instance_id {ec2_id}")

# Connect through SSM
aws ssm start-session --profile @(profile) --region @(region) --target @(ec2_id)

To import objects from .xsh files, add this to init.py:

from xonsh.main import setup
setup()
del setup

Result​

asciicast

I couldn't find any articles that helped with these examples.

Helm vs Python validation

· 3 min read

My colleagues and I needed to generate Karpenter Provisioner manifests in a loop. The container runtime choice had significant consequences. If we left provisioner.spec.kubeletConfiguration.containerRuntime unset in a Provisioner paired with an AWSNodeTemplate, Karpenter would default to containerd (see the test).

We came up with these requirements:

  • If the Provisioner omits the CRI, pick our default, which was dockerd.
  • If the Provisioner specifies a CRI, use it.
  • Handle the case where the CRI is omitted but provisioner.spec.kubeletConfiguration has other settings.

Here's the validation code we ended up with:

helm​

# Kubelet
# If Provisioner.kubeletConfiguration is not empty
{{- if .kubeletConfiguration }}
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
{{- if hasKey .kubeletConfiguration "containerRuntime" -}}
{{- toYaml .kubeletConfiguration | nindent 4 }}
# ElseIf containerRuntime has not been configured in Provisioner.kubeletConfiguration
{{- else }}
# Pick default CRI from karpenter.default.kubeletConfiguration and add it to current .kubeletConfiguration
{{- $CRI := dict "containerRuntime" $.Values.karpenter.default.kubeletConfiguration.containerRuntime -}}
{{- $kubeletConfiguration := merge $CRI .kubeletConfiguration }}
{{- toYaml $kubeletConfiguration | nindent 4 }}
{{- end }}
# ElseIf Provisioner.kubeletConfiguration is empty
{{- else }}
kubeletConfiguration:
{{- toYaml $.Values.karpenter.default.kubeletConfiguration | nindent 4 }}
{{- end }}
Tests

Test cases:

    1. The Provisioner omits the CRI values.yml
karpenter:
payload:
ahorbach:
foo: bar

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
containerRuntime: dockerd
    1. The Provisioner specifies the CRI

values.yml

karpenter:
payload:
ahorbach:
kubeletConfiguration:
bar: baz
containerRuntime: rocket

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
bar: baz
containerRuntime: rocket
# ElseIf containerRuntime has not been configured in Provisioner.kubeletConfiguration
# ElseIf Provisioner.kubeletConfiguration is empty
    1. The Provisioner omits the CRI but provides other configuration

values.yml

payload:
ahorbach:
kubeletConfiguration:
spam: eggs

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
# Pick default CRI from karpenter.default.kubeletConfiguration and add it to current .kubeletConfiguration
containerRuntime: dockerd
spam: eggs

python​

from pydantic import BaseModel, validator

DEFAULT_CRI = {"containerRuntime": "dockerd"}

class karpenterPayloadProvisioner(BaseModel):
name: str
kubelet_configuration: dict = DEFAULT_CRI

@validator('kubelet_configuration')
def kubelet_container_runtime(cls, v):
cri = v.get("containerRuntime")
# option two - Mutating
if cri not in ["dockerd", "containerd"]:
v.update(DEFAULT_CRI)
return v
Tests
import typing as t

import pytest

from karpenter import karpenterPayloadProvisioner

# without selected CRI in Provisioner
case1 = ("foo", {}, "dockerd")

# with containerd as a CRI for Provisioner

case2 = ("bar", {"kubeReserved": "testMe", "containerRuntime": "containerd"}, "containerd")

# with typo in CRI for Provisioner
case3 = ("baz", {"kubeReserved": "testMe", "containerRuntime": "qwerty"}, "dockerd")

test_cases = [
case1,
case2,
case3,
]

@pytest.mark.parametrize("name, kubelet_configuration, expected_CRI", test_cases)
def test_cri_provisioner(name: str, kubelet_configuration: t.Optional[dict], expected_CRI: str):

provisioner = karpenterPayloadProvisioner(name=name, kubelet_configuration=kubelet_configuration)
assert provisioner.kubelet_configuration["containerRuntime"] == expected_CRI

pytest .
=========================================================== test session starts ============================================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/a.horbach/repository-self/python-monorepo/pydantic-karpenter
plugins: django-4.4.0, cov-3.0.0
collected 3 items

test_karpenter.py ... [100%]

============================================================ 3 passed in 0.08s =============================================================