view k8s_ops.py @ 20:f5777b65f035

fast update of scrape_main.yaml
author drewp@bigasterisk.com
date Sat, 24 Jun 2023 01:44:57 -0700
parents
children cd115f1ca2a8
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, configObj):
    api_instance = client.CoreV1Api()
    api_response = api_instance.replace_namespaced_config_map(  #
        name=name,
        namespace='default',
        body={
            'apiVersion': 'v1',
            'kind': 'ConfigMap',
            'metadata': {
                'name': name
            },
            'data': {
                'scrape_main': json.dumps(configObj)
            },
        })
    print(f"{name} resource_version is now {api_response.metadata.resource_version}")