You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure Runbook Python脚本连接AKS集群并管理K8s资源

问题描述

我是DevOps新手,希望通过Azure Runbook的Python脚本连接AKS集群,实现删除Pod等资源的操作。本地环境中,我们先登录az账号,再执行两条命令连接AKS;现在想了解如何通过Runbook Python脚本实现类似操作,管理Pod、Deployment、Service等Kubernetes资源。我使用了以下Azure Python SDK脚本,但运行报错(已创建自动化RunAsAccount):

from kubernetes import client, config
from kubernetes.client.rest import ApiException

# config.load_incluster_config()
# config.load_kube_config()

config.load_incluster_config()
configuration = client.Configuration()

with client.ApiClient(configuration) as api_client:
    api_instance = client.CoreV1Api(api_client)
  
    namespace = 'default' # str | see @Max Lobur's answer on how to get this
    name = 'PodName' # str | Pod name, e.g. via api_instance.list_namespaced_pod(namespace)
    
    try:
        api_response = api_instance.delete_namespaced_pod(name, namespace)
        print(api_response)
    except ApiException as e:
        print("Exception when calling CoreV1Api->delete_namespaced_pod: %s\n" % e)

运行报错信息:

Failed
Traceback (most recent call last):  File "C:\Temp\trfoszt2.pnq\abb1bda8-2ca8-4a11-8ce9-d75a880004fa", line 237, in <module>    config.load_incluster_config()  File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\kubernetes\config\incluster_config.py", line 118, in load_incluster_config    InClusterConfigLoader(  File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\kubernetes\config\incluster_config.py", line 54, in load_and_set    self._load_config()  File "C:\WPy64-3800\python-3.8.0.amd64\lib\site-packages\kubernetes\config\incluster_config.py", line 62, in _load_config    raise ConfigException("Service host/port is not set.")kubernetes.config.config_exception.ConfigException: Service host/port is not set.
解决方案

错误原因

config.load_incluster_config() 是为运行在AKS集群内部的Pod设计的,它会读取集群内部的服务账户凭证。而Azure Runbook运行在Azure自动化服务环境中,不在AKS集群内,所以会抛出Service host/port is not set的错误。

正确实现步骤

需要通过Azure自动化RunAs账户获取AKS的kubeconfig配置,再用该配置初始化Kubernetes客户端:

  1. 安装依赖包:在Azure自动化账户中导入以下Python包:

    • azure-mgmt-containerservice
    • kubernetes
    • azure-identity
  2. 修改后的脚本:

from azure.identity import DefaultAzureCredential
from azure.mgmt.containerservice import ContainerServiceClient
from kubernetes import client, config
from kubernetes.client.rest import ApiException

# 配置Azure资源信息
SUBSCRIPTION_ID = "你的订阅ID"
RESOURCE_GROUP_NAME = "AKS所在的资源组名"
AKS_CLUSTER_NAME = "AKS集群名称"

# 使用RunAs账户获取Azure凭证
credential = DefaultAzureCredential()
container_client = ContainerServiceClient(credential, SUBSCRIPTION_ID)

# 获取AKS集群的kubeconfig
kubeconfig = container_client.managed_clusters.list_cluster_user_credentials(
    RESOURCE_GROUP_NAME,
    AKS_CLUSTER_NAME
).kubeconfigs[0].value.decode('utf-8')

# 将kubeconfig加载到Kubernetes客户端
config.load_kube_config(config_file=None, context=None, client_configuration=None, persist_config=False, yaml_content=kubeconfig)

# 初始化Kubernetes API客户端
v1_api = client.CoreV1Api()

# 删除指定Pod
namespace = "default"
pod_name = "要删除的Pod名称"

try:
    response = v1_api.delete_namespaced_pod(
        name=pod_name,
        namespace=namespace,
        body=client.V1DeleteOptions()
    )
    print(f"Pod删除成功:{response}")
except ApiException as e:
    print(f"删除Pod时出错:{e}")

关键说明

  • RunAs账户权限:确保自动化RunAs账户拥有AKS集群的Microsoft.ContainerService/managedClusters/listClusterUserCredentials/action权限,以及目标命名空间的Pod删除权限(可通过AKS RBAC配置)。
  • kubeconfig获取:通过list_cluster_user_credentials API获取集群的用户kubeconfig,避免手动管理凭证文件。
  • 其他资源操作:如果要管理Deployment、Service等资源,只需替换对应的API客户端(如client.AppsV1Api()用于Deployment,client.CoreV1Api()用于Service),调用对应的方法即可。

内容的提问来源于stack exchange,提问作者Vinay Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 09:15:31