Azure Windows VM - how can I find out what Resource Group it is in?

妖精的绣舞 提交于 2021-01-28 04:27:56

问题


I have C# code running on an Azure Windows VM. Is there a way for me to find out what Resource Group this VM is in?

VM has been deployed with Azure Resource Management API (new, not classic)


回答1:


The following will guarantee the ability to distinguish between vm's with the same name across different resource groups:

From your C# code, find the vmId (involves running one of the commands at the following link or possibly using an Azure SDK: https://azure.microsoft.com/en-us/blog/accessing-and-using-azure-vm-unique-id/). If using a Linux VM, be sure to take into account the different endian-ness, otherwise the vmId will not match.

Once you have the vmId, you can use either CLI or Powershell (or potentially an Azure SDK) to list all of the VM's in the subscription, then search through the list to find which VM has the vmId you got from the machine. Then you should be able to parse out the resource group name from the "id" field of the json for that VM (which, as Gaurav mentioned, is a string with the resource group in it). For an example, try the following:

azure vm list --json -vv

This command will show you the url's it is using to make the requests and the response body. In this body you will find the "vmId" and "id" field. For instance, one of the requests it sends is:

https://management.azure.com/subscriptions/{my-subscription-id}/providers/Microsoft.Compute/virtualMachines?api-version=2015-06-15

and the response body for this is the json with the relevant entries. Hope this helps! :)




回答2:


One way to find out the resource group is to list all the virtual machines in your Azure Subscription. The URL you would use for that would be:

https://management.azure.com/subscriptions/[subscription-id]/providers/Microsoft.Compute/virtualMachines?api-version=2015-06-15

It will return you a list of all Virtual Machines in your Azure Subscription in JSON format where each item represents a Virtual Machine. You can first filter by the name property to find the matching Virtual Machine. Then the property which is important to you there is id which is always of the format:

/subscriptions/[subscription-id]/resourceGroups/[resource-group-name]/providers/Microsoft.Compute/virtualMachines/[virtual-machine-name]

You could simply parse this to get the resource group name.




回答3:


How did you deploy the VM? Through portal.azure.com? Through CLI? Powershell? In any of these cases, usually you are required to specify a resource group name. In fact, in the portal, if you click on "Virtual Machines", it should say the resource group:

resource group of VM in portal




回答4:


write-host(Get-AzVm -name "hostname").ResourceGroupName



来源:https://stackoverflow.com/questions/33716805/azure-windows-vm-how-can-i-find-out-what-resource-group-it-is-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!