Mendi Neymark
Mendi Neymark

Reputation: 816

how to get kubectl configuration from azure aks with python?

I create a k8s deployment script with python, and to get the configuration from kubectl, I use the python command:

from kubernetes import client, config

config.load_kube_config()

to get the azure aks configuration I use the following az commands:

az login
az aks get-credentials --resource-group [resource group name] --name [aks name]

is there any way to get azure aks credential only from python and without the need of the az commands?

thanks!

Upvotes: 7

Views: 5880

Answers (3)

Dave Hirschfeld
Dave Hirschfeld

Reputation: 768

Just expanding on @user1110502's excellent answer, the kubeconfig you get is a CredentialResult object. You can turn that into a yaml string which can then be saved as a file like below:

aks_client = ContainerServiceClient(credential, subscription_id)
result: CredentialResult = aks_client.managed_clusters.list_cluster_user_credentials(
    "resourcegroup-name", "cluster-name"
).kubeconfigs[0]
kubeconfig: str = result.value.decode("utf-8")

To then use this config in the kubernetes python library you could save it as a file and load it in the usual manner with kubernetes.config.load_kube_config, however the same can be achieved without the unnecessary disk IO like below:

import yaml
import kubernetes
from kubernetes.config.kube_config import KubeConfigLoader

cfg_dict = yaml.safe_load(kubeconfig)
loader = KubeConfigLoader(cfg_dict)
config = client.Configuration()
loader.load_and_set(config)
client.Configuration.set_default(config)

The kubernetes library can then be connected to your AKS cluster:

with kubernetes.client.ApiClient(config) as api_client:
    api = client.WellKnownApi(api_client)
    resp = api.get_service_account_issuer_open_id_configuration()
    print(resp)

Upvotes: 2

user1110502
user1110502

Reputation: 100

Yes, this can be done with the Azure Python SDK.

from azure.identity import DefaultAzureCredential
from azure.mgmt.containerservice import ContainerServiceClient

credential = DefaultAzureCredential(exclude_cli_credential=True)
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
container_service_client = ContainerServiceClient(credential, subscription_id)

kubeconfig = container_service_client.managed_clusters.list_cluster_user_credentials("resourcegroup-name", "cluster-name").kubeconfigs[0]

Upvotes: 3

4c74356b41
4c74356b41

Reputation: 72151

In this case the solution was to use Azure Python SDK to retrieve cluster credentials directly from Azure API bypassing Az Cli.

https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2019_11_01/operations/_managed_clusters_operations.py#L320

Upvotes: -1

Related Questions