在azure python sdk上过滤虚拟机

s3fp2yjn  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(104)

我一直在尝试过滤虚拟机,同时使用ComputeClientManager列表函数获取它。根据文档,列表函数的第二个参数是一个字符串,表示过滤虚拟机的过滤器。
这就是函数:compute_client.virtual_machines.list(resource_group_name,filter_str)
文档页面:https://learn.microsoft.com/en-us/python/api/azure-mgmt-compute/azure.mgmt.compute.v2022_08_01.operations.virtualmachinesoperations?view=azure-python#azure-mgmt-compute-v2022-08-01-operations-virtualmachinesoperations-list
不幸的是,我不能理解构造这个字符串的正确语法是什么,因为即使是文档中的字符串示例似乎也不起作用。
我找不到一个合适的解释来在Python中构建这些字符串并使其正确过滤。我想基于标签进行过滤,例如运行机器。任何有效的字符串过滤器的示例都将受到高度赞赏,或者一些带有示例的源代码。
多谢了!
在尝试从list函数返回的迭代器中获取vm后,我得到了这种类型的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "/home/azureuser/.local/lib/python3.8/site-packages/azure/core/paging.py", line 132, in __next__
    return next(self._page_iterator)
  File "/home/azureuser/.local/lib/python3.8/site-packages/azure/core/paging.py", line 76, in __next__
    self._response = self._get_next(self.continuation_token)
  File "/home/azureuser/.local/lib/python3.8/site-packages/azure/mgmt/compute/v2022_11_01/operations/_virtual_machines_operations.py", line 2229, in get_next
    raise HttpResponseError(response=response, error_format=ARMErrorFormat)
azure.core.exceptions.HttpResponseError: (ProviderError) Resource provider 'Microsoft.Compute' failed to return collection response for type 'virtualMachines'.
Code: ProviderError
Message: Resource provider 'Microsoft.Compute' failed to return collection response for type 'virtualMachines'.
iaqfqrcu

iaqfqrcu1#

在Azure python SDK上筛选虚拟机
要使用Python使用筛选器列出位于**subscription level**的Azure虚拟机,可以使用以下代码:

验证码:

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient

subscription_id="Your-subscription-id"
credential = DefaultAzureCredential()
compute_client = ComputeManagementClient(credential, subscription_id)

vms = compute_client.virtual_machines.list_all()

for vm in vms:
   if vm.tags is not None and 'Reason' in vm.tags: #This part is filter
      print(vm.name)

输出:

sabodRHEL8.1Todel
    azurestoragetestvm
    lineofsight
    vmlinux
    ruk123
    vm326

要使用Python使用筛选器列出位于**resource-group level**的Azure虚拟机,您可以使用以下代码:

验证码:

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient

    subscription_id="Your-subscription-id"
    credential = DefaultAzureCredential()
    resource_grp="Your-resourcegrp-name"
    compute_client = ComputeManagementClient(credential, subscription_id)

    vms = compute_client.virtual_machines.list(resource_group_name=resource_grp)

    for vm in vms:
          if vm.tags is not None and 'Reason' in vm.tags:
             print(vm.name)

输出:

vm326

相关问题