简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM