import asyncio import base64 import yaml from kubernetes_asyncio.client.api_client import ApiClient from kubernetes_asyncio import client, config from os import path from time import time LABEL_MANAGED_BY = "camera-operator" with open("camera-service.yml") as stream: SERVICE_BODY = stream.read() with open("camera-deployment.yml") as stream: DEPLOYMENT_BODY = stream.read() async def main(): await config.load_kube_config() async with ApiClient() as api: v1 = client.CoreV1Api(api) apps_api = client.AppsV1Api() print("Listing namespaces") ret = await v1.list_namespace() api_instance = client.CustomObjectsApi(api) now = str(time()) for i in ret.items: try: resp = await api_instance.list_namespaced_custom_object( "k-space.ee", "v1alpha1", i.metadata.name, "cams") except client.exceptions.ApiException: continue for item in resp["items"]: target = item["spec"]["target"] secret_ref = item["spec"].get("secretRef") replicas = item["spec"].get("replicas") print("Applying", target) name = "camera-%s" % item["metadata"]["name"] # Generate Deployment body = yaml.safe_load(DEPLOYMENT_BODY.replace("foobar", name)) body["metadata"]["labels"] ["app.kubernetes.io/managed-by"] = LABEL_MANAGED_BY body["metadata"]["labels"] ["modified"] = now body["spec"]["template"]["spec"]["containers"][0]["args"] = [target] if replicas: body["spec"]["replicas"] = replicas try: await apps_api.replace_namespaced_deployment( name = name, body = body, namespace=i.metadata.name) print("Updated deployment %s/%s" % (i.metadata.name, name)) except client.exceptions.ApiException as e: await apps_api.create_namespaced_deployment( body = body, namespace=i.metadata.name) print("Created deployment %s/%s" % (i.metadata.name, name)) # Generate Service body = yaml.safe_load(SERVICE_BODY.replace("foobar", name)) body["metadata"]["labels"] ["app.kubernetes.io/managed-by"] = LABEL_MANAGED_BY body["metadata"]["labels"] ["modified"] = now try: await v1.replace_namespaced_service( name = name, body = body, namespace=i.metadata.name) print("Updated service %s/%s" % (i.metadata.name, name)) except client.exceptions.ApiException as e: await v1.create_namespaced_service( body = body, namespace=i.metadata.name) print("Created service %s/%s" % (i.metadata.name, name)) deployments = await apps_api.list_deployment_for_all_namespaces() for dep in deployments.items: if not dep.metadata.labels: continue if dep.metadata.labels.get("app.kubernetes.io/managed-by") != LABEL_MANAGED_BY: continue if dep.metadata.labels.get("modified") == now: continue print("Removing deployment: %s/%s" % (dep.metadata.namespace, dep.metadata.name)) await apps_api.delete_namespaced_deployment(name=dep.metadata.name, namespace=dep.metadata.namespace) print("Done") if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close()