Powershell get Azure VM name from private IP
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-azurermvmResourceGroupName Name Location VmSize OsType NIC ProvisioningState----------------- ---- -------- ------ ------ --- -----------------RGNAME jason eastus Standard_A1 Linux jason66 SucceededPS C:\> $a = ((Get-AzureRmNetworkInterface | ?{$_.IpConfigurations.PrivateIpAddress -eq '10.0.0.4'}).VirtualMachine).IDPS C:\> $vmname = ($a -split '/') | select -Last 1PS C:\> $vmnamejason
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