Skip to main content

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.

Comments and reactions