다음을 통해 공유


Azure Virtual Machines에 대한 Azure Resource Graph 샘플 쿼리

이 페이지는 Azure Virtual Machines에 대한 Azure Resource Graph 샘플 쿼리 모음입니다.

샘플 쿼리

완료된 OS 업데이트 설치 수

지난 7일 동안 컴퓨터에 대해 수행된 OS 업데이트 설치 실행의 상태 목록을 반환합니다.

PatchAssessmentResources
| where type !has 'softwarepatches'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount)
| where lTime > ago(7d)
| project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount) | where lTime > ago(7d) | project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount"

가용성 상태 및 구독 ID별 가상 머신 수

각 구독에서 해당 가용성 상태별로 집계된 가상 머신(Microsoft.Compute/virtualMachines 형식)의 수를 반환합니다.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)"

전원 상태별 가상 머신 수

전원 상태에 따라 분류된 가상 머신 수(Microsoft.Compute/virtualMachines 형식)를 반환합니다. 전원 상태에 대한 자세한 내용은 전원 상태 개요를 참조하세요.

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)"

OS 유형별로 가상 머신 개수 계산

이전 쿼리를 토대로 작성되며 Microsoft.Compute/virtualMachines 종류의 Azure 리소스에 의해 제한되지만 반환되는 레코드 수가 더 이상 제한되지 않습니다. 대신 summarizecount()를 사용하여 속성(이 예제에서 properties.storageProfile.osDisk.osType)별로 값을 그룹화하고 집계하는 방법을 정의했습니다. 전체 개체에서 이 문자열이 나타나는 방법에 대한 예제를 보려면 리소스 탐색 - 가상 머신 검색을 참조하세요.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by tostring(properties.storageProfile.osDisk.osType)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by tostring(properties.storageProfile.osDisk.osType)"

OS 유형별로 가상 머신 개수 계산(extend 사용)

‘OS 유형별 가상 머신 계산’ 쿼리를 작성하는 다른 방법은 속성을 extend하고 쿼리 내에서 사용할 임시 이름(이 경우 os)을 지정하는 것입니다. 그런 다음, os는 참조된 예에서와 같이 summarizecount()에서 사용됩니다.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| extend os = properties.storageProfile.osDisk.osType
| summarize count() by tostring(os)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | extend os = properties.storageProfile.osDisk.osType | summarize count() by tostring(os)"

지난 30일 동안의 모든 새 경고 가져오기

이 쿼리는 지난 30일 동안 모든 사용자의 새 경고 목록을 제공합니다.

iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/alerts'
| where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/alerts' | where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'"

가상 머신 스케일링 집합 용량 및 크기 가져오기

이 쿼리는 가상 머신 확장 집합 리소스를 찾고 가상 머신 크기 및 확장 집합의 용량을 포함하는 다양한 세부 정보를 가져옵니다. 이 쿼리는 toint() 함수를 사용하여 정렬할 수 있도록 용량을 숫자로 캐스팅합니다. 마지막으로, 열의 이름이 사용자 지정 명명 속성으로 바뀝니다.

Resources
| where type=~ 'microsoft.compute/virtualmachinescalesets'
| where name contains 'contoso'
| project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name
| order by Capacity desc
az graph query -q "Resources | where type=~ 'microsoft.compute/virtualmachinescalesets' | where name contains 'contoso' | project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name | order by Capacity desc"

가상 머신에 설치된 모든 확장 나열

먼저, 이 쿼리는 가상 머신 리소스 유형의 extend를 사용하여 ID를 대문자(toupper())로 가져오고, 운영 체제 이름 및 유형을 가져오고, 가상 머신 크기를 가져옵니다. 리소스 ID를 대문자로 가져오는 것은 다른 속성에 조인하기 위해 준비하는 데 좋은 방법입니다. 그런 다음, 쿼리는 확장 ID의 대문자를 일치시켜 가상 머신 확장을 가져오는 데 사용합니다 joinleftouterkind.substring 이전 /extensions/\<ExtensionName\> ID 부분은 가상 머신 ID와 동일한 형식이므로 이 속성을 join사용합니다. summarizeID, OSName, OSTypeVMSize 단일 배열 속성으로 동일한 각 확장의 이름을 결합하기 위해 가상 머신 확장의 이름에 사용됩니다make_list. 마지막으로 OSName order by 을 .으로 asc소문자로 지정합니다. 기본적으로 order by는 내림차순입니다.

Resources
| where type == 'microsoft.compute/virtualmachines'
| extend
  JoinID = toupper(id),
  OSName = tostring(properties.osProfile.computerName),
  OSType = tostring(properties.storageProfile.osDisk.osType),
  VMSize = tostring(properties.hardwareProfile.vmSize)
| join kind=leftouter(
  Resources
  | where type == 'microsoft.compute/virtualmachines/extensions'
  | extend
    VMId = toupper(substring(id, 0, indexof(id, '/extensions'))),
    ExtensionName = name
) on $left.JoinID == $right.VMId
| summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize
| order by tolower(OSName) asc
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend JoinID = toupper(id), OSName = tostring(properties.osProfile.computerName), OSType = tostring(properties.storageProfile.osDisk.osType), VMSize = tostring(properties.hardwareProfile.vmSize) | join kind=leftouter( Resources | where type == 'microsoft.compute/virtualmachines/extensions' | extend  VMId = toupper(substring(id, 0, indexof(id, '/extensions'))),  ExtensionName = name ) on \$left.JoinID == \$right.VMId | summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize | order by tolower(OSName) asc"

모든 머신에 사용 가능한 OS 업데이트를 업데이트 범주별로 나열

컴퓨터에서 보류 중인 OS 목록을 반환합니다.

PatchAssessmentResources
| where type !has 'softwarepatches'
| extend prop = parse_json(properties)
| extend lastTime = properties.lastModifiedDateTime
| extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType
| project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend prop = parse_json(properties) | extend lastTime = properties.lastModifiedDateTime | extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType | project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount"

완료된 Linux OS 업데이트 설치 목록

지난 7일 동안 컴퓨터에 대해 수행된 Linux Server - OS 업데이트 설치 실행의 상태 목록을 반환합니다.

PatchAssessmentResources
| where type has 'softwarepatches' and properties has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState | sort by RunID"

리소스 ID별 가상 머신 및 관련 가용성 상태 목록

가용성 상태별로 집계된 가상 머신(Microsoft.Compute/virtualMachines 형식)의 최신 목록을 반환합니다. 또한 쿼리는 쉽게 디버깅하고 완화할 수 있는 관련 리소스 ID를 기반으로 properties.targetResourceId합니다. 가용성 상태는 사용 가능한 값, 사용할 수 없음, 성능 저하 및 알 수 없음의 네 가지 값 중 하나일 수 있습니다. 각 가용성 상태의 의미에 대한 자세한 내용은 Azure Resource Health 개요를 참조하세요.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

리소스 ID 및 리소스 그룹을 사용하는 가용성 상태 및 전원 상태별 가상 머신 목록

가상 머신의 일관된 상태를 제공하기 위해 전원 상태와 가용성 상태에 대해 집계된 가상 머신 목록(Microsoft.Compute/virtualMachines 형식)을 반환합니다. 또한 쿼리는 리소스에 대한 자세한 가시성을 위해 각 항목과 연결된 리소스 그룹 및 리소스 ID에 대한 세부 정보를 제공합니다.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code)
| join kind=leftouter (
  HealthResources
  | where type =~ 'microsoft.resourcehealth/availabilitystatuses'
  | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines'
  | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState))
  on $left.Id == $right.targetResourceId
| project-away targetResourceId
| where PowerState != 'PowerState/deallocated'
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code) | join kind=leftouter ( HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines' | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on \$left.Id == \$right.targetResourceId | project-away targetResourceId | where PowerState != 'PowerState/deallocated'"

리소스 ID에서 사용할 수 없는 가상 머신 목록

가용성 상태별로 집계된 가상 머신(Microsoft.Compute/virtualMachines 형식)의 최신 목록을 반환합니다. 채워진 목록은 가용성 상태가 사용할 수 없는 가상 머신만 강조 표시하여 가상 머신이 있는 모든 관련 상태를 인식할 수 있도록 합니다. 모든 가상 머신을 사용할 수 있는 경우 결과가 나타나지 않습니다.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.availabilityState) != 'Available'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.availabilityState) != 'Available' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

완료된 Windows Server OS 업데이트 설치 목록

지난 7일 동안 컴퓨터에 대해 수행된 Windows Server - OS 업데이트 설치 실행의 상태 목록을 반환합니다.

PatchAssessmentResources
| where type has 'softwarepatches' and properties !has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties !has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState | sort by RunID"

네트워크 인터페이스 및 공용 IP를 사용하여 가상 머신 나열

이 쿼리는 두 leftouterjoin 가지 명령을 사용하여 Resource Manager 배포 모델, 관련 네트워크 인터페이스 및 해당 네트워크 인터페이스와 관련된 공용 IP 주소를 사용하여 만든 가상 머신을 함께 가져옵니다.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend nics=array_length(properties.networkProfile.networkInterfaces)
| mv-expand nic=properties.networkProfile.networkInterfaces
| where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic)
| project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id)
| join kind=leftouter (
  Resources
  | where type =~ 'microsoft.network/networkinterfaces'
  | extend ipConfigsCount=array_length(properties.ipConfigurations)
  | mv-expand ipconfig=properties.ipConfigurations
  | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true'
  | project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id))
  on nicId
| project-away nicId1
| summarize by vmId, vmName, vmSize, nicId, publicIpId
| join kind=leftouter (
  Resources
  | where type =~ 'microsoft.network/publicipaddresses'
  | project publicIpId = id, publicIpAddress = properties.ipAddress)
on publicIpId
| project-away publicIpId1
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | extend nics=array_length(properties.networkProfile.networkInterfaces) | mv-expand nic=properties.networkProfile.networkInterfaces | where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic) | project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id) | join kind=leftouter ( Resources | where type =~ 'microsoft.network/networkinterfaces' | extend ipConfigsCount=array_length(properties.ipConfigurations) | mv-expand ipconfig=properties.ipConfigurations | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true' | project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id)) on nicId | project-away nicId1 | summarize by vmId, vmName, vmSize, nicId, publicIpId | join kind=leftouter ( Resources | where type =~ 'microsoft.network/publicipaddresses' | project publicIpId = id, publicIpAddress = properties.ipAddress) on publicIpId | project-away publicIpId1"

이름의 내림차순으로 모든 가상 머신 나열

가상 머신(type이 Microsoft.Compute/virtualMachines로 지정됨)만 나열하려면 결과에서 type 속성만 매칭하면 됩니다. 이전 쿼리와 마찬가지로 descorder by를 내림차순으로 변경합니다. 형식 일치의 =~는 Resource Graph에 대/소문자를 구분하지 않도록 알립니다.

Resources
| project name, location, type
| where type =~ 'Microsoft.Compute/virtualMachines'
| order by name desc
az graph query -q "Resources | project name, location, type | where type =~ 'Microsoft.Compute/virtualMachines' | order by name desc"

이름 및 해당 OS 유형별로 처음 5개의 가상 머신 표시

이 쿼리는 top을 사용하여 이름별로 정렬된 5개 일치 레코드만 검색합니다. Azure 리소스의 형식은 Microsoft.Compute/virtualMachines입니다. project는 Azure Resource Graph에 포함할 속성을 알려 줍니다.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| project name, properties.storageProfile.osDisk.osType
| top 5 by name desc
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project name, properties.storageProfile.osDisk.osType | top 5 by name desc"

전원 상태 확장 속성을 기준으로 가상 머신 요약

이 쿼리는 가상 머신의 확장 속성을 사용하여 전원 상태별로 요약합니다.

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by tostring(properties.extended.instanceView.powerState.code)"

정규식과 일치하는 가상 머신

이 쿼리는 정규식(regex로 알려짐)과 일치하는 가상 머신을 찾습니다. matches regex @는 일치시킬 정규식을 정의할 수 있으며, ^Contoso(.*)[0-9]+$입니다. 해당 regex 정의는 다음으로 설명되어 있습니다.

  • ^ - 일치는 문자열의 시작 부분에서 시작해야 합니다.
  • Contoso - 대/소문자 구분 문자열입니다.
  • (.*) - 하위 식 일치:
    • . - 단일 문자를 일치시킵니다(새 줄 제외).
    • * - 이전 요소를 0번 이상 일치시킵니다.
  • [0-9] - 0~9의 숫자에 대한 문자 그룹 일치입니다.
  • + - 이전 요소를 한 번 이상 일치시킵니다.
  • $ - 이전 요소의 일치는 문자열의 끝에서 발생해야 합니다.

이름으로 일치시킨 후 쿼리는 이름 오름차순으로 이름 및 순서를 프로젝션합니다.

Resources
| where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+$'
| project name
| order by name asc
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+\$' | project name | order by name asc"

다음 단계