如何不使用Client ID和Secret ID通过Python启停Azure VM?
无需Client ID和Secret ID实现Azure VM启停的Python方案
当然可以不用Client ID和Secret ID来操作Azure VM,下面是几种实用的替代方案,适配不同的运行场景:
适用场景及对应代码
1. 本地开发:用Azure CLI已登录的身份
如果你已经在本地通过az login命令登录过Azure CLI,可以直接复用这个身份,不需要额外凭证:
from azure.identity import AzureCliCredential from azure.mgmt.compute import ComputeManagementClient subscription_id = '<你的订阅ID>' # 调用Azure CLI的登录身份 credential = AzureCliCredential() # 初始化Compute客户端 compute_client = ComputeManagementClient(credential, subscription_id) resource_group_name = '<虚拟机所在资源组名>' vm_name = '<虚拟机名称>' # 执行停止VM操作(释放资源) result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name) # 如需启动VM,替换为下面一行: # result = compute_client.virtual_machines.start(resource_group_name, vm_name)
2. 本地开发:交互式浏览器登录
如果不想用Azure CLI,也可以通过弹出浏览器窗口完成登录,适合临时测试:
from azure.identity import InteractiveBrowserCredential from azure.mgmt.compute import ComputeManagementClient subscription_id = '<你的订阅ID>' # 触发浏览器登录弹窗 credential = InteractiveBrowserCredential() compute_client = ComputeManagementClient(credential, subscription_id) resource_group_name = '<虚拟机所在资源组名>' vm_name = '<虚拟机名称>' # 停止VM result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name)
3. 云环境:用Azure托管身份(最安全)
如果你的代码运行在Azure内部资源(比如Azure VM、Function App、App Service)上,推荐用托管身份——Azure会自动管理凭证,全程不用手动配置任何密钥:
- 先给运行代码的Azure资源(比如你的应用所在VM)启用托管身份(系统分配或用户分配均可)
- 给这个托管身份赋予目标VM的「启动/停止」权限(比如添加
Virtual Machine Contributor角色,或者更精细的自定义权限)
然后代码如下:
from azure.identity import ManagedIdentityCredential from azure.mgmt.compute import ComputeManagementClient subscription_id = '<你的订阅ID>' # 系统分配托管身份直接初始化 credential = ManagedIdentityCredential() # 如果是用户分配的托管身份,需要指定其Client ID: # credential = ManagedIdentityCredential(client_id="<用户分配托管身份的Client ID>") compute_client = ComputeManagementClient(credential, subscription_id) resource_group_name = '<虚拟机所在资源组名>' vm_name = '<虚拟机名称>' # 停止VM result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name)
注意事项
- 以上方案都基于Azure SDK for Python的新身份认证库
azure-identity,需要先安装依赖:pip install azure-identity azure-mgmt-compute - 托管身份方案仅适用于Azure内部资源,本地开发无法使用
内容的提问来源于stack exchange,提问作者Rohit Mishra
相关产品推荐
相关产品推荐

