I need to use Azure Python SDK and Kubernetes Python Client to list the Pods CPU limits for a cluster running in AKS.
Although its straight forward using CLI/PowerShell but I need to use Python exclusively.
Must not use subprocess calls.
Here is snippet that gets KubeConfig
object after authentication with Azure:
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerservice import ContainerServiceClient
credential = DefaultAzureCredential(exclude_cli_credential=True)
subscription_id = "XXX"
resource_group_name= 'MY-SUB'
cluster_name = "my-aks-clustername"
container_service_client = ContainerServiceClient(credential, subscription_id)
kubeconfig = container_service_client.managed_clusters.
list_cluster_user_credentials(resource_group_name, cluster_name).
kubeconfigs[0]
But I am unsure how to put this to be used by K8s Python client:
from kubernetes import client, config
config.load_kube_config() ## How to pass?
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%st%st%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
3
Answers
You can use the
config.load_kube_config
method and pass in the kubeconfig object you obtained earlier as a parameter. The method accepts aconfig_file
parameter, which can be a file object, a file-like object, or a string file path.Since kubeconfig is a string, you can pass it as a string file path, like so:
I tried a repro and was able to achieve as below –
Getting kubeconfig in correct decoded format from kubeconfigs[0] which is CredentialResults.
Writing the generated kubeconfig in a file.
Loading the file in config module.