Feed Python Kubernetes client with heredoc instead of filepath

5/27/2020

Is there a simple way to create a configuration object for the Python Kubernetes client by passing a variable containing the YAML of the kubeconfig?

It's fairly easy to do something like:

from kubernetes import client, config, watch
def main():
    config.load_kube_config()

or

from kubernetes import client, config, watch
def main():
    config.load_incluster_config()

But I will like to create the config based on a variable with the YAML kubeconfig, Let's say I have:

k8s_config = yaml.safe_load('''
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://asdf.asdf:443
  name: cluster
contexts:
- context:
    cluster: cluster
    user: admin
  name: admin
current-context: admin
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate-data: LS0tVGYUZiL2sxZlRFTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    client-key-data: LS0tLS1CRUdJTiBSU0EgU0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=
''')

And I will like to load it as:

config.KubeConfigLoader(k8s_config)

The reason for this is that I can't store the content of the kubeconfig before loading the config.

The error I'm receiving is: "Error: module 'kubernetes.config' has no attribute 'KubeConfigLoader'"

-- ccamacho
kubernetes
kubernetes-python-client
python

1 Answer

5/28/2020

They don't include KubeConfigLoader in the "pull up" inside config/__init__.py, which is why your kubernetes.config.KubeConfigLoader reference isn't working. You will have to reach into the implementation package and reference the class specifically:

from kubernetes.config.kube_config import KubeConfigLoader

k8s_config = yaml.safe_load('''...''')
config = KubeConfigLoader(
    config_dict=k8s_config,
    config_base_path=None)

Be aware that unlike most of my answers, I didn't actually run this one, but that's the theory

-- mdaniel
Source: StackOverflow