Explore seus recursos do Azure com o Gráfico de RecursosExplore your Azure resources with Resource Graph

O Gráfico de Recursos do Azure fornece a capacidade de explorar e descobrir seus recursos do Azure rapidamente e em escala.Azure Resource Graph provides the ability to explore and discover your Azure resources quickly and at scale. Projetado para respostas rápidas, é uma ótima maneira de aprender sobre seu ambiente e também sobre as propriedades que existem em seus recursos do Azure.Engineered for fast responses, it's a great way to learn about your environment and also about the properties that exist on your Azure resources.

Explore máquinas virtuaisExplore virtual machines

Um recurso comum no Azure é uma máquina virtual.A common resource in Azure is a virtual machine. Assim como um tipo de recurso, as máquinas virtuais têm muitas propriedades que podem ser consultadas.As a resource type, virtual machines have many properties that can be queried. Cada propriedade fornece uma opção para filtrar ou encontrar exatamente o recurso que você está procurando.Each property provides an option for filtering or finding exactly the resource you're looking for.

Descoberta de máquina virtualVirtual machine discovery

Vamos começar com uma consulta simples para obter uma única VM do nosso ambiente e observar as propriedades retornadas.Let's start with a simple query to get a single VM from our environment and look at the properties returned.

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" | ConvertTo-Json -Depth 100

Observação

O cmdlet Search-AzGraph do Azure PowerShell retorna um PSCustomObject por padrão.The Azure PowerShell Search-AzGraph cmdlet returns a PSCustomObject by default. Para que a saída tenha a mesma aparência do que é retornado pela CLI do Azure, o cmdlet ConvertTo-Json é usado.To have the output look the same as what is returned by Azure CLI, the ConvertTo-Json cmdlet is used. O valor padrão da Profundidade é 2.The default value for Depth is 2. Ao definir como 100, ele deve converter todos os níveis retornados.Setting it to 100 should convert all returned levels.

Os resultados do JSON são estruturados de forma semelhante ao exemplo a seguir:The JSON results are structured similar to the following example:

[
  {
    "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"
  }
]

As propriedades nos dizem informações adicionais sobre o recurso de máquina virtual em si.The properties tell us additional information about the virtual machine resource itself. Essas propriedades incluem: sistema operacional, discos, marcas e o grupo de recursos e a assinatura da qual é membro.These properties include: operating system, disks, tags, and the resource group and subscription it's a member of.

Máquinas virtuais por localizaçãoVirtual machines by location

Tomando o que aprendemos sobre o recurso de máquinas virtuais, vamos usar a propriedade location para contar todas as máquinas virtuais por local.Taking what we learned about the virtual machines resource, let's use the location property to count all virtual machines by location. Para atualizar a consulta, removeremos o limite e resumiremos a contagem dos valores de localização.To update the query, we'll remove the limit and summarize the count of location values.

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"

Os resultados do JSON são estruturados de forma semelhante ao exemplo a seguir:The JSON results are structured similar to the following example:

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

Agora podemos ver quantas máquinas virtuais temos em cada região do Azure.We can now see how many virtual machines we have in each Azure region.

Máquinas virtuais por SKUVirtual machines by SKU

Voltando às propriedades originais da máquina virtual, vamos tentar encontrar todas as máquinas virtuais que possuem um tamanho de SKU Standard_B2s.Going back to the original virtual machine properties, let's try to find all the virtual machines that have a SKU size of Standard_B2s. Olhando para o JSON retornado, vemos que ele está armazenado em properties.hardwareprofile.vmsize.Looking at the JSON returned, we see that it's stored in properties.hardwareprofile.vmsize. Atualizaremos a consulta para encontrar todas as VMs que correspondam a esse tamanho e retornemos apenas o nome da VM e região.We'll update the query to find all VMs that match this size and return just the name of the VM and region.

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"

Máquinas virtuais conectadas a discos gerenciados premiumVirtual machines connected to premium-managed disks

Para obter os detalhes dos discos gerenciados Premium que estão anexados a essas máquinas virtuais Standard_B2s , expandimos a consulta para retornar a ID de recurso desses discos gerenciados.To get the details of premium-managed disks that are attached to these Standard_B2s virtual machines, we expand the query to return the resource ID of those managed disks.

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"

O resultado é uma lista de IDs de disco.The result is a list of disk IDs.

Descoberta de disco gerenciadoManaged disk discovery

Com o primeiro registro da consulta anterior, exploraremos as propriedades que existem no disco gerenciado que foi anexado à primeira máquina virtual.With the first record from the previous query, we'll explore the properties that exist on the managed disk that was attached to the first virtual machine. A consulta atualizada usa a ID do disco e altera o tipo.The updated query uses the disk ID and changes the type.

Exemplo de saída da consulta anterior, por exemplo:Example output from the previous query for example:

[
  {
    "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'

Antes de executar a consulta, como sabemos que o tipo deve ser agora Microsoft.Compute / disks?Before running the query, how did we know the type should now be Microsoft.Compute/disks? Se você olhar para o ID completo, você verá /providers/Microsoft.Compute/disks/ como parte da cadeia de caracteres.If you look at the full ID, you'll see /providers/Microsoft.Compute/disks/ as part of the string. Esse fragmento de cadeia de caracteres fornece uma dica sobre o tipo de pesquisa.This string fragment gives you a hint as to what type to search for. Um método alternativo seria remover o limite por tipo e, em vez disso, pesquisar apenas pelo campo ID.An alternative method would be to remove the limit by type and instead only search by the ID field. Como o ID é exclusivo, apenas um registro seria retornado e a propriedade tipo nele fornece esse detalhe.As the ID is unique, only one record would be returned and the type property on it provides that detail.

Observação

Para este exemplo funcionar, você deve substituir o campo ID por um resultado de seu próprio ambiente.For this example to work, you must replace the ID field with a result from your own environment.

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'"

Os resultados do JSON são estruturados de forma semelhante ao exemplo a seguir:The JSON results are structured similar to the following example:

[
  {
    "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"
  }
]

Explore máquinas virtuais para encontrar endereços IP públicosExplore virtual machines to find public IP addresses

Esse conjunto de consultas primeiro encontra e armazena todos os recursos de NIC (adaptadores de rede) conectados às máquinas virtuais.This set of queries first finds and stores all the network interfaces (NIC) resources connected to virtual machines. Em seguida, as consultas usam a lista de NICs para encontrar cada recurso de endereço IP que seja um endereço IP público e armazenar esses valores.Then the queries use the list of NICs to find each IP address resource that is a public IP address and store those values. Por fim, as consultas apresentam uma lista de endereços IP públicos.Finally, the queries provide a list of the public IP addresses.

# 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"

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

Use o arquivo (CLI do Azure) ou a variável (Azure PowerShell) na próxima consulta para obter os detalhes dos recursos da interface de rede relacionados, em que há um endereço IP público conectado ao NIC.Use the file (Azure CLI) or variable (Azure PowerShell) in the next query to get the related network interface resources details where there's a public IP address attached to the 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"

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

Por último, use a lista de recursos de endereços IP públicos armazenados no arquivo (CLI do Azure) ou na variável (Azure PowerShell) para obter o endereço IP público real deles e exibi-los.Last, use the list of public IP address resources stored in the file (Azure CLI) or variable (Azure PowerShell) to get the actual public IP address from the related object and display.

# 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"

Para ver como realizar essas etapas em uma única consulta com o operador join, veja o exemplo em Listar máquinas virtuais com a interface de rede e o IP público.To see how to accomplish these steps in a single query with the join operator, see the List virtual machines with their network interface and public IP sample.

Próximas etapasNext steps