簡體   English   中英

有沒有辦法找出給定 VM 的資源組,然后使用 Python sdk 在 Azure 中找出 VM 的詳細信息

[英]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 的詳細信息

有人可以指出我正確的例子嗎?

我想做的是

  • 輸入私有 ip 的 azure vm
  • 需要找出這台 azure 機器所在的資源組
  • 然后它應該在該資源管理組下獲取上述 vm 的 vm 詳細信息

如果您只知道虛擬機的名稱,唯一的方法是通過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.

如果您還有更多問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM