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

如何使用Azure Python SDK获取Azure LoadBalancer相关配置信息

实现获取Azure负载均衡器指定字段Python字典的方案

前置依赖

首先安装需要的Azure Python SDK包,执行以下命令:
pip install azure-mgmt-network azure-identity

操作代码

核心是调用Azure官方SDK的负载均衡器查询接口,利用SDK内置的as_dict()方法将资源对象转为原生Python字典,再按你要求的字段提取组装即可:

from azure.identity import DefaultAzureCredential
from azure.mgmt.network import NetworkManagementClient

# 请替换为你的实际配置参数
AZURE_SUBSCRIPTION_ID = "替换为你的Azure订阅ID"
RESOURCE_GROUP = "替换为负载均衡器所在的资源组名称"
LOAD_BALANCER_NAME = "替换为目标负载均衡器的名称"

# 初始化Azure认证客户端
cred = DefaultAzureCredential()
network_client = NetworkManagementClient(cred, AZURE_SUBSCRIPTION_ID)

# 查询负载均衡器详情
lb_instance = network_client.load_balancers.get(
    resource_group_name=RESOURCE_GROUP,
    load_balancer_name=LOAD_BALANCER_NAME
)

# 组装符合要求的字典
output_dict = {
    "FrontEndIP's": [cfg.as_dict() for cfg in lb_instance.frontend_ip_configurations],
    "Backend Pools": [pool.as_dict() for pool in lb_instance.backend_address_pools],
    "Probes": [probe.as_dict() for probe in lb_instance.probes],
    "Rules": [rule.as_dict() for rule in lb_instance.load_balancing_rules]
}

# 可直接打印或后续处理该字典
print(output_dict)

注意事项

本地运行代码前请先执行az login登录你的Azure账号,DefaultAzureCredential会自动读取本地登录凭证完成认证;如果是在Azure云上运行服务,可以直接绑定托管身份,无需额外配置认证信息。
如果你不需要每个配置的全量字段,可以自行替换as_dict()方法,手动提取你需要的字段即可,例如只提取前端IP的名称和地址:{"name": cfg.name, "ip": cfg.private_ip_address or (cfg.public_ip_address.ip_address if cfg.public_ip_address else None)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:15:03