如何使用python从azure aks获取kubectl配置?

x33g5p2x  于 2023-04-22  发布在  Python
关注(0)|答案(3)|浏览(158)

我用python创建了一个k8s部署脚本,并使用python命令从kubectl获取配置:

from kubernetes import client, config

config.load_kube_config()

要获取Azure aks配置,我使用以下az命令:

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

有没有办法只从python获取azure aks凭证,而不需要az命令?
谢谢!

yhqotfr8

yhqotfr81#

可以,这可以通过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]
9w11ddsr

9w11ddsr2#

在这种情况下,解决方案是使用Azure Python SDK绕过Az Cli直接从Azure API检索群集凭据。
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

neekobn8

neekobn83#

只是扩展@user1110502的优秀答案,你得到的kubeconfig是一个CredentialResult对象。你可以把它转换成一个yaml字符串,然后可以保存为一个文件,如下所示:

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")

然后在kubernetes python库中使用此配置,您可以将其保存为文件并以kubernetes.config.load_kube_config的常规方式加载它,但是可以在没有不必要的磁盘IO的情况下实现相同的功能,如下所示:

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)

然后可以将kubernetes库连接到您的AKS集群:

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

相关问题