This data provider allows for a connection to the Azure Resource Graph and a way to query against the Azure Resource Graph Explorer. The data connector functions in the same way as other data connectors and uses the Kusto Query Language (KQL) and has with some subtle differences to other connectors in they way that authentication is handled.
You would use this data connector to flexibly and quickly get details on deployed Azure resources within a subscription. It allows for bulk queries on various aspects of resources and returns data in a very structured format. This makes it much more effective and efficient than getting resource specific details via the resource API.
More details about data providers in MSTICPy can be found in the documentation
Installation of this data connector requires that MSTICPy be installed with the Azure extras:
pip install msticpy['azure']
The provider for the Azure Resource Graph is named ResourceGraph
from msticpy.data.data_providers import QueryProvider
qry_prov = QueryProvider("ResourceGraph")
Once initialized the first step in using the data provider is to authenticate. The Resource Graph provider uses MSTICPy's Azure authentication features and you can provide a set of authentication methods when connecting. By default the provider will attempt to authenticate using credentials stored in msticpyconfig.yaml (or as environment variables) and an Azure CLI connection but this can be customized with the 'auth_methods' keyword.
If storing details in msticpyconfig.yaml they must be under the AzureCLI
DataProviders section - for more details see this documentation.
Once successfully connected you will be presented with a "Connected" message.
qry_prov.connect(auth_methods=["cli"])
Connected
As with other data providers there are a number of built-in queries with this provider. Once connected you can view the available queries with QUERY_PROVIDER.list_queries()
.
Alternatively you can view query details in an interactive widget with QUERY_PROVIDER.browse_queries()
For more information, refer documentation : Listing available queries.
qry_prov.browse_queries()
VBox(children=(Text(value='', description='Filter:', style=DescriptionStyle(description_width='initial')), Sel…
Parameters
Query
{table} | where type =~ "microsoft.compute/virtualmachines" | where name contains "{host_name}" | 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 {add_query_items}
Example
{QueryProvider}[.QueryPath].QueryName(params...)
qry_prov.ResourceGraph.list_detailed_virtual_machines(start=start, end=end, hostname=host)
In order to run pre-defined query, execute with the query name, e.g. QUERY_PROVIDER.ResoruceGraph.QUERY_NAME()
. You can pass parameters to these queries to customize them, however they will also run with default parameters if none as provider. The query browser will provide details as to what parameters are avaliable with each query.
As with other data providers data is returned to you in a Pandas DataFrame.
For more information , refer documentation - Running an pre-defined query
qry_prov.ResourceGraph.list_resources_by_api_version()
type | apiVersion | |
---|---|---|
0 | microsoft.alertsmanagement/actionrules | 2019-05-05-preview |
1 | microsoft.alertsmanagement/smartdetectoralertr... | 2021-04-01 |
2 | microsoft.apimanagement/service | 2019-12-01 |
3 | microsoft.automanage/accounts | 2020-06-30-preview |
4 | microsoft.automation/automationaccounts | 2018-06-30 |
... | ... | ... |
161 | microsoft.web/serverfarms | 2020-10-01 |
162 | microsoft.web/sites | 2019-08-01 |
163 | microsoft.web/sites/slots | 2019-08-01 |
164 | microsoft.web/staticsites | 2019-12-01-preview |
165 | sendgrid.email/accounts | 2015-01-01 |
166 rows × 2 columns
You can also define a your own KQL query for the Resource Graph and run with QUERY_PROVIDER.exec_query(QUERY)
For more information, see the documentation on Running an Ad-hoc Query
query = "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | take 3"
qry_prov.exec_query(query)
id | name | type | tenantId | kind | location | resourceGroup | subscriptionId | managedBy | sku | ... | tags.azsecpack | identity.userAssignedIdentities./subscriptions/8eebd9ad-e271-4989-a796-d60c57655743/resourceGroups/AzSecPackAutoConfigRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/AzSecPackAutoConfigUA-eastus2.principalId | identity.userAssignedIdentities./subscriptions/8eebd9ad-e271-4989-a796-d60c57655743/resourceGroups/AzSecPackAutoConfigRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/AzSecPackAutoConfigUA-eastus2.clientId | identity.type | identity | properties.storageProfile.osDisk.vhd.uri | properties.osProfile.windowsConfiguration.patchSettings.patchMode | properties.osProfile.windowsConfiguration.provisionVMAgent | properties.osProfile.windowsConfiguration.enableAutomaticUpdates | properties.diagnosticsProfile.bootDiagnostics.storageUri | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | /subscriptions/8eebd9ad-e271-4989-a796-d60c576... | RHEL77Base | microsoft.compute/virtualmachines | 72f988bf-86f1-41af-91ab-2d7cd011db47 | eastus2 | linuxtestlab | 8eebd9ad-e271-4989-a796-d60c57655743 | None | ... | nonprod | e660337c-1cc7-4818-b8c8-3f005dbc6f2a | 5fae63c7-985a-4432-9ff2-ef6ff0dc7db6 | UserAssigned | NaN | NaN | NaN | NaN | NaN | NaN | ||
1 | /subscriptions/8eebd9ad-e271-4989-a796-d60c576... | Ubuntu18ASC | microsoft.compute/virtualmachines | 72f988bf-86f1-41af-91ab-2d7cd011db47 | eastus2 | linuxtestlab | 8eebd9ad-e271-4989-a796-d60c57655743 | None | ... | nonprod | e660337c-1cc7-4818-b8c8-3f005dbc6f2a | 5fae63c7-985a-4432-9ff2-ef6ff0dc7db6 | UserAssigned | NaN | NaN | NaN | NaN | NaN | NaN | ||
2 | /subscriptions/8eebd9ad-e271-4989-a796-d60c576... | GodzillaTron1 | microsoft.compute/virtualmachines | 72f988bf-86f1-41af-91ab-2d7cd011db47 | japanwest | monster-island | 8eebd9ad-e271-4989-a796-d60c57655743 | None | ... | NaN | NaN | NaN | NaN | NaN | https://monsterislanddisks868.blob.core.window... | AutomaticByOS | True | True | https://monsterislanddiag271.blob.core.windows... |
3 rows × 58 columns
In this example we want to take a look at all of the virtual machines we have in our environment and they get specific details including public IP on one of them:
from msticpy.data.data_providers import QueryProvider
# Initialize and connect to provider
qry_prov = QueryProvider("ResourceGraph")
qry_prov.connect()
Connected
# Get list of VMs and see how many we have
vms = qry_prov.ResourceGraph.list_virtual_machines()
print(f"Number of VMs found : {len(vms.index)}")
# Filter the query to get a smaller dataset
vms = qry_prov.ResourceGraph.list_virtual_machines(add_query_items="| where resourceGroup contains 'msticpy'")
display(vms)
# Set hostname for our next query
hostname = vms.iloc[0]['name']
Number of VMs found : 418
id | name | type | tenantId | kind | location | resourceGroup | subscriptionId | managedBy | sku | ... | properties.extended.instanceView.powerState.displayStatus | properties.extended.instanceView.powerState.level | properties.extended.instanceView.powerState.code | properties.vmId | properties.diagnosticsProfile.bootDiagnostics.enabled | tags.platformsettings.host_environment.service.platform_optedin_for_rootcerts | tags.azsecpack | identity.principalId | identity.tenantId | identity.type | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | /subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f... | MSTIC-DSVM | microsoft.compute/virtualmachines | 72f988bf-86f1-41af-91ab-2d7cd011db47 | eastus | msticpy | 40dcc8bf-0478-4f3b-b275-ed0a94f2c013 | None | ... | VM deallocated | Info | PowerState/deallocated | 280b7966-c42f-4730-b993-62bef12b187d | True | true | nonprod | 7eece21d-835f-432e-b049-2c3002f3879e | 72f988bf-86f1-41af-91ab-2d7cd011db47 | SystemAssigned, UserAssigned |
1 rows × 46 columns
Now we can get details on the specific VM using its hostname.
df = qry_prov.ResourceGraph.list_detailed_virtual_machines(host_name=hostname)
print(tabulate(df.head(), df.columns, tablefmt="rst", showindex=False))
# copy table to clipboard and paste in RST doc
clip.copy(tabulate(df.head(), df.columns, tablefmt="rst", showindex=False))
================================================================================================================================= ========== ============ ====================================================================================================================================== ====================================================================================================================================== ================= vmId vmName vmSize nicId publicIpId publicIpAddress ================================================================================================================================= ========== ============ ====================================================================================================================================== ====================================================================================================================================== ================= /subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f2c013/resourceGroups/MSTICpy/providers/Microsoft.Compute/virtualMachines/MSTIC-DSVM MSTIC-DSVM Standard_B2s /subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f2c013/resourceGroups/MSTICpy/providers/Microsoft.Network/networkInterfaces/mstic-dsvm832 /subscriptions/40dcc8bf-0478-4f3b-b275-ed0a94f2c013/resourceGroups/MSTICpy/providers/Microsoft.Network/publicIPAddresses/MSTIC-DSVM-ip 20.55.96.194 ================================================================================================================================= ========== ============ ====================================================================================================================================== ====================================================================================================================================== =================