Kubernetes client not configured in startup handler
rlenkov opened this issue · comments
Keywords
kubernetes startup handler api access
Problem
I was trying to run some kubernetes client operations in the startup handler but I was getting request errors from the kube API server. Later I realized that the reason was that in the @kopf.on.startup()
handler somehow kubernetes credentials are not automatically configured, as they are in event handlers.
To illustrate the point, this code failed being unable to reach the API server:
@kopf.on.startup()
def startup_operator(settings: kopf.OperatorSettings, logger, **kwargs):
api = kubernetes.client.CoreV1Api()
ns = api.list_namespace()
print(ns)
But by adding the config everything runs fine:
@kopf.on.startup()
def startup_operator(settings: kopf.OperatorSettings, logger, **kwargs):
kubernetes.config.load_kube_config()
# or kubernetes.config.load_incluster_config() to use serviceaccount when running in a pod
api = kubernetes.client.CoreV1Api()
ns = api.list_namespace()
print(ns)
Is this intentional?
Hi, please spare some time to answer this query.
Hello. This is not intentional, but it is so by design.
The startup handler is called very early in the lifecycle of an operator — much earlier than the K8s API clients are configured (in the on-login handlers). As such, there are no credentials yet — you have to login explicitly.
Noted! Thank you very much for the answer!