0

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
  • 707
  • 8
  • 22
  • It [appears](https://github.com/kubernetes-client/python-base/blob/d30f1e6fd4e2725aae04fa2f4982a4cfec7c682b/config/kube_config.py#L699-L702) that you are only showing us part of your situation, and not the whole deal, since `KubeConfigLoader` does not emit any such error message. Please do consider [editing your question](https://stackoverflow.com/posts/62050335/edit) and posting an [MCVE](https://stackoverflow.com/help/mcve) – mdaniel May 28 '20 at 03:17
  • @mdaniel yeah sorry I wasn't looking correctly the error code. I updated the answer with the correct error. – ccamacho May 28 '20 at 15:52

1 Answers1

0

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
  • 31,240
  • 5
  • 55
  • 58
  • I have been checking the documentation and it seems that using the KubeConfigLoader class uses the file as a cache in the system so passing the file should be the correct path. I believe that in order to use the kubeconfig.yml content the best way might be go with something similar to https://github.com/kubernetes-client/python/blob/master/examples/remote_cluster.py – ccamacho May 30 '20 at 15:02