Access Kubernetes clusters using python client

3/24/2019

I have my kubernetes cluster which is deployed in cloud, and I have a local proxy which I should use in order to connect my k8s cluster from my desktop. I am able to access my clusters using kubectl no issues by running a proxy. Now I am trying to see if I can eliminate kubectl command line utility by using python client utility alone.

So in my first requirment I eliminated kubectl and I am able to access my cluster using the below code. The thing is, my access token is valid for only 15 mins, post that I'll have to run my proxy with kubectl to get my refreshed token to be updated in my kubeconfig file so I would be good for next 15 mins.

so my question and looking for some advise, 1. Is there any way I can completely eliminate kubectl by just using kubernetes python client along with local proxy. 2. How do I get my refreshed token automatically so I don't have to run my proxy every 15 mins.

Any ideas/doc/example appreciated.

   from kubernetes import client, config

   def main():
     try:
        #config.load_kube_config('kubeconfig',persist_config=True)
        config.load_kube_config('kubeconfig')
        kube_host = config.kube_config.Configuration._default.host+":443"
        kube_api_key = config.kube_config.Configuration._default.api_key
        aConfiguration = client.Configuration()

        # Specify the endpoint of your Kube cluster
        aConfiguration.host = kube_host

        aConfiguration.verify_ssl = False
        aConfiguration.api_key = kube_api_key
        aApiClient = client.ApiClient(aConfiguration)

        # Do calls
        v1 = client.CoreV1Api(aApiClient)
        api_response = v1.list_namespaced_pod('default')
        print(api_response)
    except Exception as e:
        print("Exception when calling CoreV1Api->list_namespaced_pod: %s\n" % e)


     if __name__ == '__main__':
          main()
-- user8781522
kubectl
kubernetes
python

1 Answer

3/25/2019

Here is the answer: https://stackoverflow.com/a/48377444/5936468

You can create a service account and use its token for auth

-- Grigory Ignatyev
Source: StackOverflow