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

如何在Azure Runbook中使用Python对REST API进行身份验证?

在Azure自动化Python Runbook中调用Quota API的身份验证方案

核心思路

Azure自动化账户的Runbook可通过托管身份获取Azure REST API访问令牌,无需手动管理凭据,这是适配内部脚本的安全方案。

具体实现步骤

1. 启用自动化账户的系统分配托管身份

  • 进入Azure自动化账户 → 左侧菜单「身份」→ 系统分配标签 → 切换为「开启」并保存。
  • 为该托管身份分配Quota Reader(或对应权限角色)到目标订阅/资源组,确保其具备配额数据读取权限。

2. 在Runbook中获取Bearer令牌

利用Azure自动化预装的azure-identity库,通过ManagedIdentityCredential获取令牌:

from azure.identity import ManagedIdentityCredential
import requests

# 初始化托管身份凭据
credential = ManagedIdentityCredential()

# 请求Quota API所需令牌(资源标识符固定为https://management.azure.com/)
token = credential.get_token("https://management.azure.com/.default")

# 构建请求头
headers = {
    "Authorization": f"Bearer {token.token}",
    "Content-Type": "application/json"
}

3. 调用Quota List API

按API规范拼接请求URL并发起请求:

# 替换为你的订阅ID和目标区域
subscription_id = "your-subscription-id"
location = "your-region"

api_url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Capacity/resourceProviders/Microsoft.Compute/locations/{location}/quotas?api-version=2023-02-01"

# 发起GET请求
response = requests.get(api_url, headers=headers)

# 处理响应结果
if response.status_code == 200:
    quota_data = response.json()
    print(quota_data)
else:
    print(f"请求失败: {response.status_code} - {response.text}")

替代方案:使用自动化账户凭据资产

若无法使用托管身份,可创建服务主体,将其客户端ID、密钥、租户ID存入自动化账户的凭据资产,再在Runbook中读取:

from azure.identity import ClientSecretCredential
import requests

# 替换为服务主体的凭据信息
tenant_id = "your-tenant-id"
client_id = "your-client-id"
client_secret = "your-client-secret"

credential = ClientSecretCredential(tenant_id, client_id, client_secret)
token = credential.get_token("https://management.azure.com/.default")

# 后续请求步骤与托管身份方案一致

注意事项

  • 确保Runbook使用Python 3.8及以上版本,兼容azure-identity库。
  • 角色分配需等待数分钟生效,若遇权限错误,优先检查角色配置是否正确。
  • API版本请使用官方文档中的稳定版,避免因版本过期导致请求失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:40:09