简体   繁体   中英

Powershell get Azure VM name from private IP

I want to get azure VM name from IP address, I tried following to get NIC name from IP and find to which VM that NIC is attached.

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

Is there a better way to get VM name directly using VM private ?

Is there a better way to get VM name directly using VM private ?

Do you mean use VM's private IP address to get the VM's name? If I understand it correctly, we can use this PowerShell to get the VM's name:

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

You can do this with Ansible using the Metadata service:

---
- 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 }}>

Result is:

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

See API details here: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service

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