Lech Migdal
Lech Migdal

Reputation: 3984

How to get ResourceId of VM script is running on in Azure with PowerShell?

I am writing a script to setup alerts in Azure, which I'd like to run through a Custom Script extension in Azure, still one of the parameters required to run Add-AzureRmMetricAlertRule is TargetResourceId which is the ResourceId of the VM where the alert should be configured.

So now I wonder - how to get ResourceId of the current VM with PowerShell?

Everything I tried assumes that I have a ResourceName or I iterate over list of VMs in subscription, while what I am interested in is the specific instance on which the script is running.

Upvotes: 2

Views: 9916

Answers (2)

Mark Wragg
Mark Wragg

Reputation: 23415

Azure has an instance metadata service similar to to those provided by AWS/GCE. You should be able to perform the following:

CURL:

curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2019-11-01"

PowerShell:

(Invoke-RestMethod "http://169.254.169.254/metadata/instance?api-version=2019-11-01" -Headers @{Metadata = $true})

From the server to get instance metadata.

Note that with the PowerShell example above Invoke-RestMethod converts the JSON response into a PowerShell object type automatically.

This feature was requested/discussed here: https://feedback.azure.com/forums/216843-virtual-machines/suggestions/6204911-provide-virtual-machine-instance-metadata-support

Upvotes: 1

Shui shengbao
Shui shengbao

Reputation: 19223

If my understanding is right, you could use the following command to get VM's resource id.

(get-azurermvm -ResourceGroupName shuihv -Name shui).id

Also, you also could structure the id if you know VM's resource group name and VM name. Format should be like below:

/subscriptions/<subscription id>/resourceGroups/<group name>/providers/Microsoft.Compute/virtualMachines/<vm name>

Update:

As said, you could use Azure metadata to get VM's name. According VM's name, you could use Azure PowerShell to get VM's resource group name.

 $vm=get-azurermvm |Where-Object {$_.Name -eq "shui"}

$vm.ResourceGroupName

Then you could structure resource id.

Upvotes: 0

Related Questions