如何通过Azure Python SDK使用UAMI认证并管控虚拟机?
问题:Azure本地脚本如何通过用户分配托管标识(UAMI)认证,无需个人凭据?
我正在开发一款跨云平台命令行工具,用于读取、启动和停止(解除分配)虚拟机。AWS端已通过boto3实现EC2实例操作,采用受限权限IAM用户凭据认证,避免误操作敏感资源。
原本计划在Azure端通过为用户分配托管标识(UAMI)绑定自定义受限角色实现类似权限控制,但目前只能通过az login用个人凭据登录使用Azure Python SDK。想知道是否存在仅通过UAMI的client_id、subscription_id、tenant_id完成认证,且脚本仅拥有UAMI权限的方法?
之前尝试用ManagedIdentityCredential认证,代码如下:
from azure.identity import ManagedIdentityCredential client_id = <UAMI_client_id> credential = ManagedIdentityCredential(client_id=client_id)
但本地运行时(和最终用户使用场景一致)出现错误:
ImdsCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint. ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint. <some traceback> azure.core.exceptions.ServiceRequestError: <urllib3.connection.HTTPConnection object at 0xffffb9a32110>: Failed to establish a new connection: [Errno 111] Connection refused
推测该认证方式仅适用于Azure内部环境,本地无法访问IMDS端点。请问有没有无需使用用户个人凭据的替代认证方案?
可行方案:使用ClientSecretCredential结合UAMI的服务主体凭据
用户分配托管标识本质上是一种特殊的服务主体,你可以为其创建客户端密钥(client secret),然后通过ClientSecretCredential完成本地认证,这样脚本就只会拥有该UAMI的权限,无需使用个人凭据。
步骤如下:
- 为UAMI创建客户端密钥:
- 登录Azure门户,找到你的用户分配托管标识
- 进入「证书和密码」选项卡,点击「新建客户端密码」,设置过期时间后保存,记录生成的客户端密码值(仅显示一次)
- 使用
ClientSecretCredential认证:
替换之前的ManagedIdentityCredential代码,使用以下方式:from azure.identity import ClientSecretCredential from azure.mgmt.compute import ComputeManagementClient # UAMI的凭据信息 tenant_id = "<你的租户ID>" client_id = "<UAMI的client_id>" client_secret = "<刚才创建的客户端密码>" subscription_id = "<你的订阅ID>" # 创建凭据对象 credential = ClientSecretCredential( tenant_id=tenant_id, client_id=client_id, client_secret=client_secret ) # 初始化Compute客户端(用于VM操作) compute_client = ComputeManagementClient(credential, subscription_id) - 权限控制:
- 确保已为该UAMI分配了对应的自定义受限角色(比如包含
Microsoft.Compute/virtualMachines/read、Microsoft.Compute/virtualMachines/start/action、Microsoft.Compute/virtualMachines/deallocate/action权限) - 角色分配范围可以是订阅、资源组或特定VM,最小化权限
- 确保已为该UAMI分配了对应的自定义受限角色(比如包含
补充说明
ManagedIdentityCredential确实仅适用于Azure内部环境(比如VM、App Service、函数应用等),本地运行时无法访问IMDS端点,所以会报错- 客户端密钥需要妥善保管,就像AWS的IAM密钥一样,避免泄露
- 如果不想使用客户端密钥,也可以用证书凭据(
ClientCertificateCredential),安全性更高,适合生产环境
内容的提问来源于stack exchange,提问作者Joe McKeown
相关产品推荐
相关产品推荐

