Reputation: 7028
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 ?
Upvotes: 6
Views: 5248
Reputation: 1225
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://learn.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
Upvotes: 0
Reputation: 13954
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
Upvotes: 7