Use az cli to Query VM Remaining CPU Credits

When working with Azure Virtual Machines (VMs), monitoring performance metrics is essential for ensuring optimal operation. A common scenario involves tracking the CPU Credits Remaining for a B-series burstable VM instance.

Typically, we use az vm monitor metrics tail to get the CPU Credits Remaining metric:

$ az vm monitor metrics tail -g $group -n $name --metric "CPU Credits Remaining" 2>/dev/null
{
  "cost": 59,
  "interval": "PT1M",
  "namespace": "Microsoft.Compute/virtualMachines",
  "resourceregion": "xx",
  "timespan": "2024-12-02T09:25:10Z/2024-12-02T10:25:10Z",
  "value": [
    {
      "displayDescription": "Total number of credits available to burst. Only available on B-series burstable VMs",
      "errorCode": "Success",
      "id": "/subscriptions/xx/resourceGroups/xx/providers/Microsoft.Compute/virtualMachines/xx/providers/Microsoft.Insights/metrics/CPU Credits Remaining",
      "name": {
        "localizedValue": "CPU Credits Remaining",
        "value": "CPU Credits Remaining"
      },
      "resourceGroup": "Linux",
      "timeseries": [
        {
          "data": [
            {
              "average": 113.08,
              "timeStamp": "2024-12-02T09:25:00Z"
            },
...
            {
              "average": 124.48,
              "timeStamp": "2024-12-02T10:22:00Z"
            },
            {
              "average": 124.68,
              "timeStamp": "2024-12-02T10:23:00Z"
            },
            {
              "timeStamp": "2024-12-02T10:24:00Z"
            }
          ],
          "metadatavalues": []
        }
      ],
      "type": "Microsoft.Insights/metrics",
      "unit": "Count"
    }
  ]
}

Breakdown of the Command:

  1. az vm monitor metrics tail: This Azure CLI command fetches the latest metrics for a specific VM.
    • -g $group: Specifies the resource group of the VM.
    • -n $name: Specifies the name of the VM.
    • --metric "CPU Credits Remaining": Fetches the specific metric showing remaining CPU credits.
  2. 2>/dev/null: Redirects any error messages to /dev/null, effectively silencing errors. This ensures that only the valid JSON output is processed further.

Since we want get the latest CPU Credits Remaining metric, we need to parse the json output by jq:

$ az vm monitor metrics tail -g $group -n $name --metric "CPU Credits Remaining" 2>/dev/null | jq -r ".value[0].timeseries[0].data[-2]"
{
  "average": 137.48,
  "timeStamp": "2024-12-02T11:27:00Z"
}

Here we extract the second-to-last (-2) data point of the CPU Credits metric's time series for analysis because the last data point doesn't contains credit field.

References:

# az vm monitor metrics