简体   繁体   English

如何使用 PowerShell 获取在 Azure 中运行的 VM 脚本的 ResourceId?

[英]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.我正在编写一个脚本来在 Azure 中设置警报,我想通过 Azure 中的自定义脚本扩展来运行该脚本,仍然是运行Add-AzureRmMetricAlertRule所需的参数Add-AzureRmMetricAlertRuleTargetResourceId ,它是警报应该所在的 VM 的 ResourceId进行配置。

So now I wonder - how to get ResourceId of the current VM with PowerShell?所以现在我想知道 - 如何使用 PowerShell 获取当前 VM 的 ResourceId?

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.我尝试的一切都假设我有一个 ResourceName 或者我遍历订阅中的 VM 列表,而我感兴趣的是运行脚本的特定实例。

Azure has an instance metadata service similar to to those provided by AWS/GCE. Azure 有一个类似于 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.请注意,对于上面的 PowerShell 示例, Invoke-RestMethod将 JSON 响应转换为 PowerShell 对象类型。

This feature was requested/discussed here: https://feedback.azure.com/forums/216843-virtual-machines/suggestions/6204911-provide-virtual-machine-instance-metadata-support此处请求/讨论了此功能: 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.如果我的理解是正确的,您可以使用以下命令来获取 VM 的资源 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.此外,如果您知道 VM 的资源组名称和 VM 名称,也可以构造 id。 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.如上所述,您可以使用Azure 元数据来获取 VM 的名称。 According VM's name, you could use Azure PowerShell to get VM's resource group name.根据 VM 的名称,您可以使用 Azure PowerShell 获取 VM 的资源组名称。

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

$vm.ResourceGroupName

Then you could structure resource id.然后你可以构造资源ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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