Share via


고급 Resource Graph 쿼리 샘플

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

다음 고급 쿼리를 살펴보겠습니다.

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

언어 지원

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

리소스 유형 및 API 버전 표시

Resource Graph는 업데이트 중에 GET 리소스 속성에 대한 리소스 공급자 API의 미리 보기가 아닌 최신 버전을 주로 사용합니다. 경우에 따라 사용되는 API 버전이 재정의되어 결과에 더 최신 속성 또는 널리 사용되는 속성이 제공되었습니다. 다음 쿼리는 각 리소스 유형에서 속성을 수집하는 데 사용되는 API 버전을 자세히 설명합니다.

Resources
| distinct type, apiVersion
| where isnotnull(apiVersion)
| order by type asc
az graph query -q "Resources | distinct type, apiVersion | where isnotnull(apiVersion) | order by type asc"

가상 머신 확장 집합 용량 및 크기 가져오기

이 쿼리는 가상 머신 확장 집합 리소스를 찾고 가상 머신 크기 및 확장 집합의 용량을 포함하는 다양한 세부 정보를 가져옵니다. 이 쿼리는 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"

결과에서 열 제거

다음 쿼리에서는 summarize를 사용하여 구독별로 리소스를 계산하고, join을 사용하여 ResourceContainers 테이블의 구독 세부 정보와 결합한 다음, project-away를 사용하여 일부 열을 제거합니다.

Resources
| summarize resourceCount=count() by subscriptionId
| join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| project-away subscriptionId, subscriptionId1
az graph query -q "Resources | summarize resourceCount=count() by subscriptionId | join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId| project-away subscriptionId, subscriptionId1"

모든 태그 이름 나열

이 쿼리는 태그를 사용하여 시작하고 모든 고유한 태그 이름 및 해당 형식을 나열하는 JSON 개체를 빌드합니다.

Resources
| project tags
| summarize buildschema(tags)
az graph query -q "Resources | project tags | summarize buildschema(tags)"

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

이 쿼리는 정규식(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"

특정 쓰기 위치를 사용하여 Azure Cosmos DB 나열

다음 쿼리는 Azure Cosmos DB 리소스를 제한하고, mv-expand를 사용하여 properties.writeLocations와 프로젝트 관련 필드에 대한 속성 모음을 차례로 확장한 다음, ‘미국 동부’ 또는 ‘미국 서부’와 일치하는 properties.writeLocations.locationName 값으로 결과를 제한합니다.

Resources
| where type =~ 'microsoft.documentdb/databaseaccounts'
| project id, name, writeLocations = (properties.writeLocations)
| mv-expand writeLocations
| project id, name, writeLocation = tostring(writeLocations.locationName)
| where writeLocation in ('East US', 'West US')
| summarize by id, name
az graph query -q "Resources | where type =~ 'microsoft.documentdb/databaseaccounts' | project id, name, writeLocations = (properties.writeLocations) | mv-expand writeLocations | project id, name, writeLocation = tostring(writeLocations.locationName) | where writeLocation in ('East US', 'West US') | summarize by id, name"

구독 이름이 있는 키 자격 증명 모음

다음 쿼리는 kindleftouter로 사용하는 join의 복잡한 사용을 보여줍니다. 이 쿼리는 조인된 테이블을 구독 리소스로 제한하고 project를 사용하여 원래 필드 subscriptionIdSubName으로 이름이 바뀐 name 필드만 포함합니다. 필드 이름 바꾸기는 필드가 리소스에 이미 있으므로 joinname1로 추가하는 것을 방지합니다. 원래 테이블은 where를 사용하여 필터링되고 다음 project에는 두 테이블의 열이 포함됩니다. 쿼리 결과는 유형, 키 자격 증명 모음 이름 및 해당하는 구독 이름을 표시하는 모든 키 자격 증명 모음입니다.

Resources
| join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| where type == 'microsoft.keyvault/vaults'
| project type, name, SubName
az graph query -q "Resources | join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId | where type == 'microsoft.keyvault/vaults' | project type, name, SubName"

SQL Database 및 탄력적 풀 나열

다음 쿼리에서는 leftouterjoin을 사용하여 SQL Database 리소스 및 이와 관련된 탄력적 풀(있는 경우)을 함께 가져옵니다.

Resources
| where type =~ 'microsoft.sql/servers/databases'
| project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId))
| join kind=leftouter (
    Resources
    | where type =~ 'microsoft.sql/servers/elasticpools'
    | project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state)
on elasticPoolId
| project-away elasticPoolId1
az graph query -q "Resources | where type =~ 'microsoft.sql/servers/databases' | project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId)) | join kind=leftouter ( Resources | where type =~ 'microsoft.sql/servers/elasticpools' | project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state) on elasticPoolId | project-away elasticPoolId1"

네트워크 인터페이스 및 공용 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"

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

먼저, 이 쿼리는 가상 머신 리소스 유형의 extend를 사용하여 ID를 대문자(toupper())로 가져오고, 운영 체제 이름 및 유형을 가져오고, 가상 머신 크기를 가져옵니다. 대문자로 리소스 ID를 가져오는 것은 다른 속성에 조인하기 위해 준비하는 좋은 방법입니다. 그런 다음, join종류와 함께 leftouter로 사용하여 확장 ID의 대문자 substring을 일치시켜 가상 머신 확장을 가져옵니다. “/extensions/<ExtensionName>” 앞의 ID 부분은 가상 머신 ID와 동일한 형식이므로 join에 이 속성을 사용합니다. 그런 다음, summarize는 가상 머신 확장 이름에 make_list와 함께 사용하여 ID, OSName, OSTypeVMSize가 동일한 각 확장의 이름을 단일 배열 속성으로 결합합니다. 마지막으로 asc를 사용하여 OSName 소문자를 order by로 결합합니다. 기본적으로 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"

리소스 그룹에서 특정 태그를 사용하여 스토리지 계정 찾기

다음 쿼리는 innerjoin을 사용하여 스토리지 계정을 지정된 대/소문자 구분 태그 이름 및 태그 값이 있는 리소스 그룹에 연결합니다.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
    ResourceContainers
    | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
    | where tags['Key1'] =~ 'Value1'
    | project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | where tags['Key1'] =~ 'Value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

대/소문자를 구분하지 않는 태그 이름 및 태그 값을 검색해야 하는 경우에는 bagexpansion 매개 변수와 함께 mv-expand를 사용합니다. 이 쿼리는 이전 쿼리보다 많은 할당량을 사용하므로 필요한 경우에만 mv-expand를 사용합니다.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
    ResourceContainers
    | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
    | mv-expand bagexpansion=array tags
    | where isnotempty(tags)
    | where tags[0] =~ 'key1' and tags[1] =~ 'value1'
    | project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | mv-expand bagexpansion=array tags | where isnotempty(tags) | where tags[0] =~ 'key1' and tags[1] =~ 'value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

두 쿼리의 결과를 단일 결과로 결합

다음 쿼리에서는 union을 사용하여 ResourceContainers 테이블에서 결과를 가져오고 Resources 테이블의 결과에 추가합니다.

ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5
| union  (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5 | union  (Resources | project name, type | limit 5)"

네트워크 인터페이스의 가상 네트워크 및 서브넷 가져오기

정규식 parse를 사용하여 리소스 ID 속성에서 가상 네트워크 및 서브넷 이름을 가져옵니다. parse를 사용하여 복합 필드에서 데이터를 가져올 수 있지만 속성이 있는 경우에는 parse를 사용하는 대신 속성에 직접 액세스하는 것이 좋습니다.

Resources
| where type =~ 'microsoft.network/networkinterfaces'
| project id, ipConfigurations = properties.ipConfigurations
| mvexpand ipConfigurations
| project id, subnetId = tostring(ipConfigurations.properties.subnet.id)
| parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet
| project id, virtualNetwork, subnet
az graph query -q "Resources | where type =~ 'microsoft.network/networkinterfaces' | project id, ipConfigurations = properties.ipConfigurations | mvexpand ipConfigurations | project id, subnetId = tostring(ipConfigurations.properties.subnet.id) | parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet | project id, virtualNetwork, subnet"

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

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

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

다음 단계