#!/usr/bin/env python3 import os import time import subprocess from kubernetes import client, config from kubernetes.client.api import CoreV1Api from kubernetes.client.models import V1ConfigMap NAMESPACE = os.getenv("NAMESPACE", "default") CONFIGMAP_NAME = "python-app-config" APP_DEPLOYMENT = "python-app" APP_CONTAINER = "python-app" def load_kube_config(): try: config.load_incluster_config() except Exception: config.load_kube_config() def get_current_image_tag() -> str: v1 = CoreV1Api() cm = v1.read_namespaced_config_map(CONFIGMAP_NAME, NAMESPACE) return cm.data.get("IMAGE_TAG", "latest") def set_deployment_image(new_tag: str): image = f"repositry.talutasku.ee/v2/my-python-app:{new_tag}" cmd = [ "kubectl", "set", "image", f"deployment/{APP_DEPLOYMENT}", f"{APP_CONTAINER}={image}", "--namespace", NAMESPACE ] subprocess.run(cmd, check=True) def watch_configmap(): v1 = CoreV1Api() last_tag = None print(f"Watching ConfigMap {CONFIGMAP_NAME} in namespace {NAMESPACE}...") while True: try: current_tag = get_current_image_tag() if current_tag != last_tag: print(f"ConfigMap updated: IMAGE_TAG={current_tag}") set_deployment_image(current_tag) last_tag = current_tag except Exception as e: print(f"Error: {e}") time.sleep(5) if __name__ == "__main__": load_kube_config() watch_configmap()