【问题标题】:Is there a way to find out Resource group for a given VM and then find out details of VM in Azure using Python sdk有没有办法找出给定 VM 的资源组,然后使用 Python sdk 在 Azure 中找出 VM 的详细信息
【发布时间】:2020-10-29 00:46:02
【问题描述】:

我在这里参考了各种文章,但没有找到确切的解决方案

有没有办法找出给定 VM 的资源组,然后使用 Python sdk 找出 Azure 中 VM 的详细信息

有人能给我指出正确的例子吗?

我想做的是

  • 输入 azure vm 的私有 ip
  • 需要找出这台天蓝色机器所在的资源组
  • 那么它应该在该资源管理组下获取上述虚拟机的虚拟机详细信息

【问题讨论】:

  • 关于“一个给定的虚拟机”,你有虚拟机名称还是别的什么?

标签: python azure sdk virtual-machine


【解决方案1】:

如果你只知道虚拟机的名称,唯一的办法就是通过list_all()方法列出所有虚拟机->然后通过它的名称选择指定的虚拟机。

注意:这里的风险在于,虚拟机的名称在不同的资源组中不是唯一的。因此,在不同的资源组中可能存在多个相同的虚拟机。你应该处理好这个案子。

示例代码:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient

SUBSCRIPTION_ID = 'xxxx'
VM_NAME = 'xxxx'

credentials = ServicePrincipalCredentials(
    client_id='xxxxx',
    secret='xxxxx',
    tenant='xxxxx'
)

compute_client = ComputeManagementClient(
    credentials=credentials,
    subscription_id=SUBSCRIPTION_ID
)

vms = compute_client.virtual_machines.list_all()

myvm_resource_group=""

for vm in vms:
    if vm.name == VM_NAME:
        print(vm.id)

        #the vm.id is always in this format: 
        #'/subscriptions/your_subscription_id/resourceGroups/your_resource_group/providers/Microsoft.Compute/virtualMachines/your_vm_name'
        #so you can split it into list, and the resource_group_name's index is always 4 in this list.
        temp_id_list=vm.id.split('/')
        myvm_resource_group=temp_id_list[4]

print("**********************!!!!!!!!!!")

print("the vm test0's resource group is: " + myvm_resource_group)

# now you know the vm name and it's resourcegroup, you can use other methods,
# like compute_client.virtual_machines.get(resource_group_name, vm_name) to do any operations for this vm.

如果您还有其他问题,请告诉我。

【讨论】:

  • 嗨,Ivan Yang,它有帮助。实际上现在我需要 fecth、标记信息、实例信息(如 cpu、类型等)以及磁盘信息、root 和交换等
  • @asp,现在你可以获取vm实例,然后尝试查找该vm实例是否有这样的属性/方法(如vm.tag或vm.type等)。如果您无法弄清楚,请在评论中@我。我想继续努力。
  • 让我试试,如果我需要帮助,一定让你知道..
  • 我正在尝试获取实例详细信息,但我没有获得所有值,参考用于描述实例的文档但无法找到完整的信息。我正在查看以 json 格式输出的以下项目对于虚拟机.. resource groupname,status,Operating system,Size,Location ,Public Ip Address,VirtualNetwork/subnet Availability Zone,Private Ip,Static IP,VM Generation, Size: Size,vcpu,RAM, Disk:OS Disk,Azure disk encryption,Data Disks Volumes::Name,Size,Storage Account,Ecnryption Volume Tags: its Key and value Backup:Backup pre-check,Last backup status,Backu poliy:its name needed
  • 是否有一种描述 vm 类型的 coomand 可以提供上述属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2019-02-21
相关资源
最近更新 更多