Search code examples
azureazure-virtual-machineazure-resource-manager

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


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)


Solution

  • 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! :)