Kaynak Grafiği ile Azure kaynaklarınızı keşfedin

Azure Kaynak Grafı, Azure kaynaklarınızı hızlı ve uygun ölçekte keşfetmenize ve keşfetmenize yardımcı olur. Hızlı yanıtlar için tasarlanmış olan bu yöntem, ortamınız ve Azure kaynaklarınızda bulunan özellikler hakkında bilgi edinmek için harika bir yoldur.

Dekont

Kaynak Grafı tablosuna bağlı olarak, özellikler Azure portalında gösterildiği gibi büyük/küçük harfle eşleşecek veya küçük harfe dönüştürülecektir. Örneğin, tabloyu sorgularken resourceContainers kaynak grubunun adı portalla eşleşecektir, ancak resourceGroup tablodaki resources kaynakların özelliği küçük harf olacaktır. Bu beklenmeyen sonuçlara neden olabilir ve işleviyle tolower() birleşimlerde özellikleri küçük harfe dönüştürmek yerine == büyük/küçük harfe duyarlı olmayan karşılaştırma işleçleri =~ kullanılarak sorgularınızda hesaba katılabilir.

Sanal makineleri keşfetme

Azure'daki yaygın bir kaynak bir sanal makinedir. Kaynak türü olarak sanal makinelerin sorgulanabilecek birçok özelliği vardır. Her özellik, tam olarak aradığınız kaynağı filtrelemek veya bulmak için bir seçenek sağlar.

Sanal makine bulma

Ortamımızdan tek bir sanal makine almak için basit bir sorguyla başlayalım ve döndürülen özelliklere bakalım.

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

Dekont

Azure PowerShell Search-AzGraph cmdlet'i varsayılan olarak bir PSResourceGraphResponse döndürür. Çıkışın Azure CLI tarafından döndürülenle aynı görünmesini sağlamak için, ConvertTo-Json data özelliğinde cmdlet kullanılır. Derinlik için varsayılan değer 2'dir. 100 olarak ayarlanması, döndürülen tüm düzeyleri dönüştürmelidir.

JSON sonuçları aşağıdaki örneğe benzer şekilde yapılandırılmıştır:

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

Özellikler bize sanal makine kaynağının kendisi hakkında ek bilgiler verir. Bu özellikler şunlardır: işletim sistemi, diskler, etiketler ve üyesi olduğu kaynak grubu ve abonelik.

Konuma göre sanal makineler

Sanal makineler kaynağı hakkında öğrendiklerini alarak, tüm sanal makineleri konuma göre saymak için location özelliğini kullanalım. Sorguyu güncelleştirmek için sınırı kaldırır ve konum değerlerinin sayısını özetleriz.

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

JSON sonuçları aşağıdaki örneğe benzer şekilde yapılandırılmıştır:

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

Artık her Azure bölgesinde kaç sanal makinemiz olduğunu görebiliriz.

SKU'ya göre sanal makineler

Özgün sanal makine özelliklerine geri dönüp SKU boyutu Standard_B2s olan tüm sanal makineleri bulmaya çalışalım. Döndürülen JSON, properties.hardwareprofile.vmsize dosyasında depolandığını gösterir. Bu boyuta uyan tüm VM'leri bulmak ve yalnızca VM'nin ve bölgenin adını döndürmek için sorguyu güncelleştireceğiz.

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

Premium yönetilen disklere bağlı sanal makineler

Bu Standard_B2s sanal makinelere eklenen premium yönetilen disklerin ayrıntılarını almak için sorguyu genişleterek bu yönetilen disklerin kaynak kimliğini döndüreceğiz.

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

Sonuç, disk kimliklerinin listesidir.

Yönetilen disk bulma

Önceki sorgudaki ilk kayıtla, ilk sanal makineye eklenmiş yönetilen diskte bulunan özellikleri keşfedeceğiz. Güncelleştirilmiş sorgu disk kimliğini kullanır ve türü değiştirir.

Önceki sorgudan alınan örnek çıktı örneğin:

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

Sorguyu çalıştırmadan önce türün artık Microsoft.Compute/disks olması gerektiğini nasıl bildik? Tam kimliğine bakarsanız dizenin bir parçası olarak /providers/Microsoft.Compute/disks/ ifadesini görürsünüz. Bu dize parçası size hangi tür için arama yaptığınıza ilişkin bir ipucu verir. Alternatif bir yöntem, türe göre sınırı kaldırmak ve bunun yerine yalnızca kimlik alanına göre arama yapmaktır. Kimlik benzersiz olduğundan yalnızca bir kayıt döndürülür ve üzerindeki type özelliği bu ayrıntıyı sağlar.

Dekont

Bu örneğin çalışması için Kimlik alanını kendi ortamınızdan alınan bir sonuçla değiştirmeniz gerekir.

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

JSON sonuçları aşağıdaki örneğe benzer şekilde yapılandırılmıştır:

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

Genel IP adreslerini bulmak için sanal makineleri keşfetme

Bu sorgu kümesi ilk olarak sanal makinelere bağlı tüm ağ arabirimleri (NIC) kaynaklarını bulur ve depolar. Ardından sorgular, genel IP adresi olan her IP adresi kaynağını bulmak ve bu değerleri depolamak için NIC listesini kullanır. Son olarak, sorgular genel IP adreslerinin listesini sağlar.

# 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

NIC'ye eklenmiş bir genel IP adresi olan ilgili ağ arabirimi kaynaklarının ayrıntılarını almak için sonraki sorguda dosyayı (Azure CLI) veya değişkeni (Azure PowerShell) kullanın.

# 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

Son olarak, ilgili nesneden gerçek genel IP adresini almak ve görüntülemek için dosyada (Azure CLI) veya değişkende (Azure PowerShell) depolanan genel IP adresi kaynaklarının listesini kullanın.

# 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

Bu adımları işleciyle join tek bir sorguda nasıl gerçekleştireceklerini görmek için sanal makineleri ağ arabirimi ve genel IP örneğiyle listeleme konusuna bakın.

Sonraki adımlar