所以我有以下 Python3 脚本来列出所有虚拟机。
import os, json
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient
from azure.common.credentials import ServicePrincipalCredentials
credentials = ServicePrincipalCredentials(
client_id="xxx",
secret="xxx",
tenant="xxx"
)
resource_client = ResourceManagementClient(credentials, "my-subscription")
compute_client = ComputeManagementClient(credentials, "my-subscription")
network_client = NetworkManagementClient(credentials, "my-subscription")
for vm in compute_client.virtual_machines.list_all():
print("\tVM: {}".format(vm.name))
但由于某种原因,我收到以下错误:
Traceback (most recent call last):
File "/Users/me/a/azure-test.py", line 17, in <module>
for vm in compute_client.virtual_machines.list_all():
...
File "/usr/local/lib/python3.8/site-packages/azure/core/pipeline/policies/_authentication.py", line 93, in on_request
self._token = self._credential.get_token(*self._scopes)
AttributeError: 'ServicePrincipalCredentials' object has no attribute 'get_token'
我做错了什么吗?
最佳答案
Python 的 Azure 库当前正在更新,以共享常见的云模式,例如身份验证协议(protocol)、日志记录、跟踪、传输协议(protocol)、缓冲响应和重试。
这也会稍微改变身份验证机制。在旧版本中,azure.common
中的 ServicePrincipalCredentials
用于向 Azure 进行身份验证并创建服务客户端。
在新版本中,身份验证机制已被重新设计并被azure-identity
库取代,以便为所有Azure SDK提供基于Azure Identity的统一身份验证。运行 pip install azure-identity
来获取包。
就代码而言,当时是:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
credentials = ServicePrincipalCredentials(
client_id='xxxxx',
secret='xxxxx',
tenant='xxxxx'
)
compute_client = ComputeManagementClient(
credentials=credentials,
subscription_id=SUBSCRIPTION_ID
)
现在是:
from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient
credential = ClientSecretCredential(
tenant_id='xxxxx',
client_id='xxxxx',
client_secret='xxxxx'
)
compute_client = ComputeManagementClient(
credential=credential,
subscription_id=SUBSCRIPTION_ID
)
然后,您可以将 list_all
方法与 compute_client
结合使用,照常列出所有虚拟机:
# List all Virtual Machines in the specified subscription
def list_virtual_machines():
for vm in compute_client.virtual_machines.list_all():
print(vm.name)
list_virtual_machines()
引用文献:
关于python - Azure Python SDK : 'ServicePrincipalCredentials' object has no attribute 'get_token' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64063850/