Azure-resources verkennen met Resource Graph

Met Azure Resource Graph kunt u uw Azure-resources snel en op schaal verkennen en ontdekken. Ontworpen voor snelle antwoorden, is het een uitstekende manier om meer te weten te komen over uw omgeving en over de eigenschappen die aanwezig zijn op uw Azure-resources.

Notitie

Afhankelijk van de resourcegrafiektabel komen de eigenschappen overeen met de behuizing, zoals wordt weergegeven in Azure Portal of worden ze verlaagd. De naam van een resourcegroep bij het uitvoeren van query's op de resourceContainers tabel komt bijvoorbeeld overeen met de portal, maar de resourceGroup eigenschap van resources uit de resources tabel is kleine letters. Dit kan onverwachte resultaten veroorzaken en kunnen worden verwerkt in uw query's met behulp van niet-hoofdlettergevoelige vergelijkingsoperatoren, zoals =~ in plaats van == en eigenschappen converteren naar kleine letters in joins met de tolower() functie.

Virtuele machines verkennen

Een algemene resource in Azure is een virtuele machine. Als resourcetype hebben virtuele machines veel eigenschappen die kunnen worden opgevraagd. Elke eigenschap biedt een optie voor het filteren of vinden van de resource die u zoekt.

Detectie van virtuele machines

Laten we beginnen met een eenvoudige query om één virtuele machine op te halen uit onze omgeving en de geretourneerde eigenschappen te bekijken.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| limit 1
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | limit 1"
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | limit 1").Data | ConvertTo-Json -Depth 100

Notitie

De Azure PowerShell-cmdlet Search-AzGraph retourneert standaard een PSResourceGraphResponse . Als u wilt dat de uitvoer er hetzelfde uitziet als wat wordt geretourneerd door Azure CLI, wordt de ConvertTo-Json cmdlet gebruikt voor de eigenschap Gegevens . De standaardwaarde voor Diepte is 2. Als u deze instelt op 100 , moeten alle geretourneerde niveaus worden geconverteerd.

De JSON-resultaten zijn gestructureerd zoals in het volgende voorbeeld:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/ContosoVM1",
    "kind": "",
    "location": "westus2",
    "managedBy": "",
    "name": "ContosoVM1",
    "plan": {},
    "properties": {
      "hardwareProfile": {
        "vmSize": "Standard_B2s"
      },
      "networkProfile": {
        "networkInterfaces": [
          {
            "id": "/subscriptions/<subscriptionId>/MyResourceGroup/providers/Microsoft.Network/networkInterfaces/contosovm1535",
            "resourceGroup": "MyResourceGroup"
          }
        ]
      },
      "osProfile": {
        "adminUsername": "localAdmin",
        "computerName": "ContosoVM1",
        "secrets": [],
        "windowsConfiguration": {
          "enableAutomaticUpdates": true,
          "provisionVMAgent": true
        }
      },
      "provisioningState": "Succeeded",
      "storageProfile": {
        "dataDisks": [],
        "imageReference": {
          "offer": "WindowsServer",
          "publisher": "MicrosoftWindowsServer",
          "sku": "2016-Datacenter",
          "version": "latest"
        },
        "osDisk": {
          "caching": "ReadWrite",
          "createOption": "FromImage",
          "diskSizeGB": 127,
          "managedDisk": {
            "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
            "resourceGroup": "MyResourceGroup",
            "storageAccountType": "Premium_LRS"
          },
          "name": "ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
          "osType": "Windows"
        }
      },
      "vmId": "bbb9b451-6dc7-4117-bec5-c971eb1118c6"
    },
    "resourceGroup": "MyResourceGroup",
    "sku": {},
    "subscriptionId": "<subscriptionId>",
    "tags": {},
    "type": "microsoft.compute/virtualmachines"
  }
]

De eigenschappen geven ons aanvullende informatie over de resource van de virtuele machine zelf. Deze eigenschappen zijn onder andere: besturingssysteem, schijven, tags en de resourcegroep en het abonnement waarvan het lid is.

Virtuele machines op locatie

Laten we de locatie-eigenschap gebruiken om alle virtuele machines op locatie te tellen. Als u de query wilt bijwerken, verwijderen we de limiet en vatten we het aantal locatiewaarden samen.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by location
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by location"
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by location").Data | ConvertTo-Json

De JSON-resultaten zijn gestructureerd zoals in het volgende voorbeeld:

[
  {
    "count_": 386,
    "location": "eastus"
  },
  {
    "count_": 215,
    "location": "southcentralus"
  },
  {
    "count_": 59,
    "location": "westus"
  }
]

We kunnen nu zien hoeveel virtuele machines we in elke Azure-regio hebben.

Virtuele machines per SKU

Als u teruggaat naar de oorspronkelijke eigenschappen van de virtuele machine, gaan we alle virtuele machines zoeken met een SKU-grootte van Standard_B2s. De geretourneerde JSON die wordt geretourneerd, toont aan dat deze is opgeslagen in properties.hardwareprofile.vmsize. We werken de query bij om alle VM's te vinden die overeenkomen met deze grootte en alleen de naam van de VM en regio te retourneren.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s'
| project name, resourceGroup
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | project name, resourceGroup"
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | project name, resourceGroup").Data | ConvertTo-Json

Virtuele machines die zijn verbonden met premium beheerde schijven

Als u de details wilt ophalen van premium beheerde schijven die zijn gekoppeld aan deze Standard_B2s virtuele machines, breiden we de query uit om de resource-id van deze beheerde schijven te retourneren.

Resources
| where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s'
| extend disk = properties.storageProfile.osDisk.managedDisk
| where disk.storageAccountType == 'Premium_LRS'
| project disk.id
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | extend disk = properties.storageProfile.osDisk.managedDisk | where disk.storageAccountType == 'Premium_LRS' | project disk.id"
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | extend disk = properties.storageProfile.osDisk.managedDisk | where disk.storageAccountType == 'Premium_LRS' | project disk.id").Data | ConvertTo-Json

Het resultaat is een lijst met schijf-id's.

Detectie van beheerde schijven

Met de eerste record uit de vorige query verkennen we de eigenschappen die aanwezig zijn op de beheerde schijf die is gekoppeld aan de eerste virtuele machine. De bijgewerkte query maakt gebruik van de schijf-id en wijzigt het type.

Voorbeelduitvoer van de vorige query, bijvoorbeeld:

[
  {
    "disk_id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166"
  }
]
Resources
| where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'

Hoe weten we dat het type nu Microsoft.Compute/disks moet zijn voordat u de query uitvoert? Als u de volledige id bekijkt, ziet u /providers/Microsoft.Compute/disks/ als onderdeel van de tekenreeks. Dit tekenreeksfragment geeft u een hint over het type waarnaar u moet zoeken. Een alternatieve methode is om de limiet per type te verwijderen en in plaats daarvan alleen te zoeken op het id-veld. Omdat de id uniek is, wordt er slechts één record geretourneerd en bevat de typeeigenschap daarin die details.

Notitie

In dit voorbeeld moet u het id-veld vervangen door een resultaat uit uw eigen omgeving.

az graph query -q "Resources | where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'"
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'").Data | ConvertTo-Json

De JSON-resultaten zijn gestructureerd zoals in het volgende voorbeeld:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
    "kind": "",
    "location": "westus2",
    "managedBy": "",
    "name": "ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
    "plan": {},
    "properties": {
      "creationData": {
        "createOption": "Empty"
      },
      "diskSizeGB": 127,
      "diskState": "ActiveSAS",
      "provisioningState": "Succeeded",
      "timeCreated": "2018-09-14T12:17:32.2570000Z"
    },
    "resourceGroup": "MyResourceGroup",
    "sku": {
      "name": "Premium_LRS",
      "tier": "Premium"
    },
    "subscriptionId": "<subscriptionId>",
    "tags": {
      "environment": "prod"
    },
    "type": "microsoft.compute/disks"
  }
]

Virtuele machines verkennen om openbare IP-adressen te vinden

Met deze set query's worden eerst alle netwerkinterfaces (NIC)-resources gevonden en opgeslagen die zijn verbonden met virtuele machines. Vervolgens gebruiken de query's de lijst met NIC's om elke IP-adresresource te vinden die een openbaar IP-adres is en deze waarden op te slaan. Ten slotte bieden de query's een lijst met de openbare IP-adressen.

# Use Resource Graph to get all NICs and store in the 'nics.txt' file
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project nic = tostring(properties['networkProfile']['networkInterfaces'][0]['id']) | where isnotempty(nic) | distinct nic | limit 20" --output table | tail -n +3 > nics.txt

# Review the output of the query stored in 'nics.txt'
cat nics.txt
# Use Resource Graph to get all NICs and store in the $nics variable
$nics = (Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project nic = tostring(properties['networkProfile']['networkInterfaces'][0]['id']) | where isnotempty(nic) | distinct nic | limit 20").Data

# Review the output of the query stored in the variable
$nics.nic

Gebruik het bestand (Azure CLI) of de variabele (Azure PowerShell) in de volgende query om de gerelateerde netwerkinterfacebronnen op te halen waar een openbaar IP-adres is gekoppeld aan de NIC.

# Use Resource Graph with the 'nics.txt' file to get all related public IP addresses and store in 'publicIp.txt' file
az graph query -q="Resources | where type =~ 'Microsoft.Network/networkInterfaces' | where id in ('$(awk -vORS="','" '{print $0}' nics.txt | sed 's/,$//')') | project publicIp = tostring(properties['ipConfigurations'][0]['properties']['publicIPAddress']['id']) | where isnotempty(publicIp) | distinct publicIp" --output table | tail -n +3 > ips.txt

# Review the output of the query stored in 'ips.txt'
cat ips.txt
# Use Resource Graph  with the $nics variable to get all related public IP addresses and store in $ips variable
$ips = (Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Network/networkInterfaces' | where id in ('$($nics.nic -join "','")') | project publicIp = tostring(properties['ipConfigurations'][0]['properties']['publicIPAddress']['id']) | where isnotempty(publicIp) | distinct publicIp").Data

# Review the output of the query stored in the variable
$ips.publicIp

Gebruik ten slotte de lijst met resources voor openbare IP-adressen die zijn opgeslagen in het bestand (Azure CLI) of variabele (Azure PowerShell) om het werkelijke openbare IP-adres op te halen uit het gerelateerde object en om weer te geven.

# Use Resource Graph with the 'ips.txt' file to get the IP address of the public IP address resources
az graph query -q="Resources | where type =~ 'Microsoft.Network/publicIPAddresses' | where id in ('$(awk -vORS="','" '{print $0}' ips.txt | sed 's/,$//')') | project ip = tostring(properties['ipAddress']) | where isnotempty(ip) | distinct ip" --output table
# Use Resource Graph with the $ips variable to get the IP address of the public IP address resources
(Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Network/publicIPAddresses' | where id in ('$($ips.publicIp -join "','")') | project ip = tostring(properties['ipAddress']) | where isnotempty(ip) | distinct ip").Data | ConvertTo-Json

Als u wilt zien hoe u deze stappen in één query met de join operator uitvoert, raadpleegt u de lijst met virtuele machines met hun netwerkinterface en openbare IP-voorbeeld .

Volgende stappen