view k8s_ops.py @ 72:85d9dae18656

fix up vmalert k8s objs
author drewp@bigasterisk.com
date Fri, 03 May 2024 13:33:33 -0700
parents adde35eb4773
children
line wrap: on
line source

import json
import time

from kubernetes import client


def refreshPodCmaps(pod_name, namespace="default"):
    """
    Per https://ahmet.im/blog/kubernetes-secret-volumes-delay/ there could be a while
    until k8s updates the CM volume that a pod sees. Workaround is to edit the pod annotations.
    """
    api_instance = client.CoreV1Api()

    pod = api_instance.read_namespaced_pod(name=pod_name, namespace=namespace)
    if pod.metadata.annotations is None:
        pod.metadata.annotations = {}
    pod.metadata.annotations["force-configmap-update"] = str(time.time())
    api_instance.replace_namespaced_pod(name=pod_name, namespace=namespace, body=pod)


def firstPodName(selector):
    api_instance = client.CoreV1Api()
    pod_list = api_instance.list_namespaced_pod(namespace="default", label_selector=selector)
    return pod_list.items[0].metadata.name


def hup(ctx, deployment, process_name):
    ctx.run(f"kubectl exec {deployment} -- pkill -HUP {process_name}")


def replaceCmap(name, dataObj):
    api_instance = client.CoreV1Api()

    data = dict((fn, json.dumps(obj)) for fn, obj in dataObj.items())

    try:

        existing_config_map = api_instance.read_namespaced_config_map(name, 'default')
        existing_config_map.data.update(data)
        api_response = api_instance.replace_namespaced_config_map(name, "default", existing_config_map)
    except client.rest.ApiException as e:
        if e.status == 404:
            config_map = client.V1ConfigMap()
            config_map.metadata = client.V1ObjectMeta(name=name)
            config_map.data = data
            api_response = api_instance.create_namespaced_config_map('default', config_map)
        else:
            raise

    print(f"{name} resource_version is now {api_response.metadata.resource_version}")