Reputation: 816
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
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
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
Reputation: 72151
In this case the solution was to use Azure Python SDK to retrieve cluster credentials directly from Azure API bypassing Az Cli.
Upvotes: -1