azureazure-devopsazure-cliazure-vmazure-cli2

Azure graph query to fetch VM Name and Private IP address


I am trying to filter instances based on tags. I am using the below command to list instances that have wknhscale == 'active' tag. It is working fine and returns the instance name and resource group.

az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines'| where tags['wknhscale']=='active' | project name, resourceGroup"| jq '[.data[] | {name, resourceGroup}]'

Now at the same time, I want to fetch the IP address of the Instance also. So I am using the below query, But it's not giving me any data.

az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' type =~ 'Microsoft.Compute/privateIPAddresses'| where tags['wknhscale']=='active'"


Solution

  • I am able to retrieve the Instances name and Private address using the below query.

    Note: You might have to give subscription-based (--subscription) on how your environment variables or azure config is set.

    az vm list-ip-addresses --ids $(az resource list -g test-group --query "[?type=='Microsoft.Compute/virtualMachines' && tags.wknhscale== 'active'].id" -o tsv) --query "[].{Name:virtualMachine.name, RG:virtualMachine.resourceGroup, IP:virtualMachine.network.privateIpAddresses[0]}"
    

    Output

    [
      {
        "IP": "11.190.0.42",
        "Name": "hscalenode04",
        "RG": "test-group"
      },
      {
        "IP": "11.190.0.43",
        "Name": "hscalenode03",
        "RG": "test-group"
      },
      {
        "IP": "11.190.0.44",
        "Name": "hscalenode05",
        "RG": "test-group"
      },
      {
        "IP": "11.190.0.45",
        "Name": "hscalenode02",
        "RG": "test-group"
      },
      {
        "IP": "11.190.0.46",
        "Name": "hscalenode01",
        "RG": "test-group"
      }
    ]