从私有IP获取Azure虚拟机名称的Powershell命令

6

我想从IP地址获取Azure虚拟机名称,我尝试了以下方法来获取NIC名称和找到附加到哪个虚拟机的NIC。

Get-AzureRmNetworkInterface | ForEach { $Interface = $_.Name; $IPs = $_ | Get-AzureRmNetworkInterfaceIpConfig | Select PrivateIPAddress; Write-Host $Interface $IPs.PrivateIPAddress }

是否有更好的方法直接使用VM私有IP来获取VM名称?

2个回答

7
有没有更好的方法可以直接使用虚拟机私有 IP 获取虚拟机名称?
你的意思是使用虚拟机的私有 IP 地址来获取虚拟机的名称吗? 如果我理解正确,我们可以使用以下 PowerShell 来获取虚拟机的名称:
PS C:> get-azurermvm

ResourceGroupName  Name Location      VmSize OsType     NIC ProvisioningState
-----------------  ---- --------      ------ ------     --- -----------------
RGNAME            jason   eastus Standard_A1  Linux jason66         Succeeded

PS C:\> $a = ((Get-AzureRmNetworkInterface | ?{$_.IpConfigurations.PrivateIpAddress -eq '10.0.0.4'}).VirtualMachine).ID
PS C:\> $vmname = ($a -split '/') | select -Last 1
PS C:\> $vmname
jason

0

您可以使用 Ansible 和元数据服务来完成此操作:

---
- name: Test Playbook
  hosts: 10.1.0.4
  gather_facts: no

  tasks:
  - name: Call VM metadata service to get compute fields.
    uri:
      url: http://169.254.169.254/metadata/instance/compute?api-version=2017-08-01
      return_content: yes
      headers:
        Metadata: true
    register: vm_metadata

  - set_fact:
      vm_name: "{{ vm_metadata.json.name }}"
      resource_group: "{{ vm_metadata.json.resourceGroupName }}"

  - debug: 
      msg: Adding disk to <RG={{ resource_group }}> <VM={{ vm_name }}>

结果是:

TASK [debug] *************************************************************************************************************************************************************
ok: [test-vm.eastus.cloudapp.azure.com] => {
    "msg": "Adding disk to <RG=test-rg> <VM=test-vm>"

请在此处查看API详细信息: https://learn.microsoft.com/zh-cn/azure/virtual-machines/windows/instance-metadata-service


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接