List all subscriptions under a management group with Azure Resource Graph
It is not a secret anymore that I really like Azure Resource Graph. Today I wanted to list all the subscriptions under a management group and had to adjust because I was leveraging hidden tags before on subscriptions. This data is now gone in ARG, let see how I now do it.
Meet managementGroupAncestorsChain
For the subscriptions
and managementgroups
under resourcecontainers
you have access to a property called managementGroupAncestorsChain
. This array will give you a list of the parent management groups in reversed order, from the immediate parent to the root.
This is exactly what I need to filter subscriptions for a certain parent management group. Since we cannot search into indexed properties directly, we need to expand it using mv-expand
. Doing this will create a new row in the ARG results for each item in managementGroupAncestorsChain
. From there we can filter on the name
property which correspond to the management group id of that ancestor.
Here is the query I ended up with:
resourcecontainers
| where type == 'microsoft.resources/subscriptions'
| mv-expand managementGroupParent = properties.managementGroupAncestorsChain
| where managementGroupParent.name =~ 'moamg'
| project name, id
| sort by name asc
This is useful in the portal but like mentioned in the past, the advantage with ARG is that it is well integrated with Azure CLI & Azure PowerShell.
! make sure you replace moag
in the segment where managementGroupParent.name =~ 'moamg'
to target the right management group id.
You can position yourself at any place in the management group hierarchy by providing the management group scope at the command line. In the example below, I target the root management group using $tenantId
. The management group id for the root management is the id of your AAD tenant.
Azure CLI & Az PowerShell examples
$query = "resourcecontainers | where type == 'microsoft.resources/subscriptions' | mv-expand managementGroupParent = properties.managementGroupAncestorsChain | where managementGroupParent.name =~ 'moamg' | project name, id | sort by name asc"
# Azure CLI
$tenantId = az account show --query tenantId -o tsv
az graph query -q $query --management-groups $tenantId | ConvertFrom-Json
# Azure PowerShell
$tenantId = (Get-AzContext).Tenant.Id
Search-AzGraph -Query $query -ManagementGroup $tenantId
Happy coding!