스타터 Resource Graph 쿼리 샘플

Azure Resource Graph를 사용하는 쿼리를 이해하는 첫 번째 단계는 쿼리 언어를 기본적으로 이해하는 것입니다. 아직 KQL(Kusto Query Language)에 익숙하지 않은 경우에는 KQL 자습서를 검토하여 원하는 리소스에 대한 요청을 작성하는 방법을 이해하는 것이 좋습니다.

이 문서에서는 다음 시작 쿼리를 사용합니다.

Azure 구독이 없는 경우 시작하기 전에 체험 계정을 만듭니다.

언어 지원

Azure CLI(확장을 통해) 및 Azure PowerShell(모듈을 통해)은 Azure Resource Graph를 지원합니다. 다음 쿼리를 실행하기 전에 사용자 환경이 준비되었는지 확인합니다. 선택한 셸 환경의 설치 및 유효성 검사 단계에 대해서는 Azure CLIAzure PowerShell을 참조하세요.

Azure 리소스 개수 계산

이 쿼리는 액세스 권한이 있는 구독에 있는 Azure 리소스의 개수를 반환합니다. 또한 이 쿼리는 선택한 셀에 적절한 Azure Resource Graph 구성 요소가 설치되어 있고 작동 중인지 검증하는 데도 적절합니다.

Resources
| summarize count()

기본적으로 Azure CLI는 액세스 가능한 모든 구독을 쿼리하지만 --subscriptions 매개 변수를 지정하여 특정 구독을 쿼리할 수 있습니다.

az graph query -q "Resources | summarize count()"

이 예에서는 구독 ID에 대한 변수를 사용합니다.

subid=$(az account show --query id --output tsv)
az graph query -q "Resources | summarize count()" --subscriptions $subid

관리 그룹 및 테넌트의 범위를 기준으로 쿼리할 수도 있습니다. <managementGroupId><tenantId>를 값으로 바꿉니다.

az graph query -q "Resources | summarize count()" --management-groups '<managementGroupId>'
az graph query -q "Resources | summarize count()" --management-groups '<tenantId>'

테넌트 ID에 변수를 사용할 수도 있습니다.

tenantid=$(az account show --query tenantId --output tsv)
az graph query -q "Resources | summarize count()" --management-groups $tenantid

Key Vault 리소스 개수 계산

이 쿼리는 summarize 대신 count를 사용하여 반환된 레코드 수를 계산합니다. Key Vault만 개수에 포함됩니다.

Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
az graph query -q "Resources | where type =~ 'microsoft.keyvault/vaults' | count"

리소스를 이름별로 나열

이 쿼리는 모든 종류의 리소스를 반환하지만 name, typelocation 속성만 반환합니다. order by를 사용하여 속성을 name 속성의 오름차순(asc)으로 정렬합니다.

Resources
| project name, type, location
| order by name asc
az graph query -q "Resources | project name, type, location | order by name asc"

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

가상 머신(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"

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

동일한 쿼리를 작성하는 다른 방법은 속성을 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)"

참고 항목

=~는 대/소문자를 구분하지 않는 일치를 허용하지만, 쿼리에서 속성(예: properties.storageProfile.osDisk.osType)을 사용하려면 대/소문자를 올바르게 사용해야 합니다. 속성의 대/소문자가 올바르지 않은 경우 null 또는 잘못된 값이 반환되며 그룹화 또는 요약이 올바르지 않게 됩니다.

스토리지를 포함하는 리소스 표시

일치하는 형식을 명시적으로 정의하는 대신 이 쿼리 예는 contains단어 storage가 있는 Azure 리소스를 찾습니다.

Resources
| where type contains 'storage' | distinct type
az graph query -q "Resources | where type contains 'storage' | distinct type"

모든 Azure Virtual Network 서브넷 나열

이 쿼리는 서브넷 이름 및 주소 접두사를 포함하는 Azure VNet(가상 네트워크) 목록을 반환합니다.

Resources
| where type == 'microsoft.network/virtualnetworks'
| extend subnets = properties.subnets
| mv-expand subnets
| project name, subnets.name, subnets.properties.addressPrefix, location, resourceGroup, subscriptionId
az graph query -q "Resources | where type == 'microsoft.network/virtualnetworks' | extend subnets = properties.subnets | mv-expand subnets | project name, subnets.name, subnets.properties.addressPrefix, location, resourceGroup, subscriptionId"

모든 공용 IP 주소 나열

이전 쿼리와 마찬가지로 publicIPAddresses 단어를 포함하는 형식에 해당하는 모든 항목을 찾습니다. 이 쿼리는 해당 패턴을 확장하여 properties.ipAddressisnotempty인 결과만 포함하고 properties.ipAddress만 반환하며, 결과를 상위 100개로 limit합니다. 선택한 셸에 따라 따옴표를 이스케이프해야 할 수도 있습니다.

Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| project properties.ipAddress
| limit 100
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | project properties.ipAddress | limit 100"

구독에 의해 IP 주소가 구성된 리소스 개수 계산

이전 예제 쿼리를 사용하고 summarizecount()를 추가하면 구성된 IP 주소를 갖는 리소스 구독별 목록을 가져올 수 있습니다.

Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| summarize count () by subscriptionId
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | summarize count () by subscriptionId"

특정 태그 값이 있는 리소스 나열

태그와 같은 Azure 리소스 형식 이외의 속성으로 결과를 제한할 수 있습니다. 이 예제에서는 값이 Internal이며 태그 이름이 Environment인 Azure 리소스를 필터링합니다.

Resources
| where tags.environment=~'internal'
| project name
az graph query -q "Resources | where tags.environment=~'internal' | project name"

또한 리소스의 태그와 값을 지정하려면 project 키워드에 tags 속성을 추가합니다.

Resources
| where tags.environment=~'internal'
| project name, tags
az graph query -q "Resources | where tags.environment=~'internal' | project name, tags"

특정 태그 값이 있는 모든 스토리지 계정 나열

이전 예제의 필터 기능을 결합하고 Azure 리소스 유형을 type 속성으로 필터링합니다. 이 쿼리는 또한 특정 태그 이름 및 값을 사용하여 특정한 종류의 Azure 리소스에 대한 검색을 제한합니다.

Resources
| where type =~ 'Microsoft.Storage/storageAccounts'
| where tags['tag with a space']=='Custom value'
az graph query -q "Resources | where type =~ 'Microsoft.Storage/storageAccounts' | where tags['tag with a space']=='Custom value'"

참고 항목

이 예제에서는 일치를 위해 =~ 조건 대신 ==을 사용합니다. ==은 대/소문자 구분 일치입니다.

모든 태그 및 해당 값 나열

이 쿼리는 관리 그룹, 구독 및 리소스에 대한 태그를 해당 값과 함께 나열합니다. 이 쿼리는 먼저 isnotempty() 태그가 project태그만 포함시켜 포함된 필드를 제한하는 리소스로 제한하고 mvexpandextend는 속성 모음에서 쌍으로 연결된 데이터를 가져옵니다. 그런 다음, union을 사용하여 ResourceContainers의 결과를 리소스의 동일한 결과와 결합하여 태그를 가져올 수 있는 광범위한 범위를 제공합니다. 마지막으로, 결과를 distinct 쌍 데이터로 제한하고 시스템 숨김 태그를 제외합니다.

ResourceContainers
| where isnotempty(tags)
| project tags
| mvexpand tags
| extend tagKey = tostring(bag_keys(tags)[0])
| extend tagValue = tostring(tags[tagKey])
| union (
    resources
    | where isnotempty(tags)
    | project tags
    | mvexpand tags
    | extend tagKey = tostring(bag_keys(tags)[0])
    | extend tagValue = tostring(tags[tagKey])
)
| distinct tagKey, tagValue
| where tagKey !startswith "hidden-"
az graph query -q "ResourceContainers | where isnotempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) | union (resources | where notempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) ) | distinct tagKey, tagValue | where tagKey !startswith "hidden-""

연결되지 않은 네트워크 보안 그룹 표시

이 쿼리는 네트워크 인터페이스 또는 서브넷에 연결되지 않은 NSG(네트워크 보안 그룹)를 반환합니다.

Resources
| where type =~ "microsoft.network/networksecuritygroups" and isnull(properties.networkInterfaces) and isnull(properties.subnets)
| project name, resourceGroup
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets) | project name, resourceGroup | sort by name asc"

심각도별로 정렬된 Azure Monitor 경고 나열

이 쿼리는 alertsmanagementresources 테이블을 사용하여 심각도별로 정렬된 Azure Monitor 경고를 반환합니다.

alertsmanagementresources
| where type =~ 'microsoft.alertsmanagement/alerts'
| where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now()
| project Severity = tostring(properties.essentials.severity)
| summarize AlertsCount = count() by Severity
az graph query -q "alertsmanagementresources | where type =~ 'microsoft.alertsmanagement/alerts' | where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now() | project Severity = tostring(properties.essentials.severity) | summarize AlertsCount = count() by Severity"

심각도 및 경고 상태별로 정렬된 Azure Monitor 경고 나열

이 쿼리는 alertsmanagementresources 테이블을 사용하여 심각도 및 경고 상태별로 정렬된 Azure Monitor 경고를 반환합니다.

alertsmanagementresources
| where type =~ 'microsoft.alertsmanagement/alerts'
| where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now()
| project Severity = tostring(properties.essentials.severity), AlertState = tostring(properties.essentials.alertState)
| summarize AlertsCount = count() by Severity, AlertState
az graph query -q "alertsmanagementresources | where type =~ 'microsoft.alertsmanagement/alerts' | where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now() | project Severity = tostring(properties.essentials.severity), AlertState = tostring(properties.essentials.alertState) | summarize AlertsCount = count() by Severity, AlertState"

심각도, 모니터 서비스, 대상 리소스 종류별로 정렬된 Azure Monitor 경고 나열

이 쿼리는 alertsmanagementresources 테이블을 사용하여 심각도, 모니터 서비스, 대상 리소스 종류별로 정렬된 Azure Monitor 경고를 반환합니다.

alertsmanagementresources
| where type =~ 'microsoft.alertsmanagement/alerts'
| where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now()
| project Severity = tostring(properties.essentials.severity),
MonitorCondition = tostring(properties.essentials.monitorCondition),
ObjectState = tostring(properties.essentials.alertState),
MonitorService = tostring(properties.essentials.monitorService),
AlertRuleId = tostring(properties.essentials.alertRule),
SignalType = tostring(properties.essentials.signalType),
TargetResource = tostring(properties.essentials.targetResourceName),
TargetResourceType = tostring(properties.essentials.targetResourceName), id
| summarize AlertsCount = count() by Severity, MonitorService , TargetResourceType
az graph query -q "alertsmanagementresources | where type =~ 'microsoft.alertsmanagement/alerts' | where todatetime(properties.essentials.startDateTime) >= ago(2h) and todatetime(properties.essentials.startDateTime) < now() | project Severity = tostring(properties.essentials.severity), MonitorCondition = tostring(properties.essentials.monitorCondition), ObjectState = tostring(properties.essentials.alertState), MonitorService = tostring(properties.essentials.monitorService), AlertRuleId = tostring(properties.essentials.alertRule), SignalType = tostring(properties.essentials.signalType), TargetResource = tostring(properties.essentials.targetResourceName), TargetResourceType = tostring(properties.essentials.targetResourceName), id | summarize AlertsCount = count() by Severity, MonitorService , TargetResourceType"

다음 단계