Skip to content

Commit d9eb5de

Browse files
authored
azure resource graph : fetch virtual machines (#1261)
1 parent ba4f949 commit d9eb5de

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/// Fetching Virtual Machines using Azure Resource Graph
2+
///
3+
/// The following example is similar to using the [Azure CLI's Resource Graph extension](https://learn.microsoft.com/en-us/azure/governance/resource-graph/first-query-azurecli#add-the-resource-graph-extension).
4+
///
5+
/// `az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines'" | jq .data[].id`
6+
///
7+
/// Ref: <https://learn.microsoft.com/en-us/rest/api/azureresourcegraph/resourcegraph(2021-03-01)/resources/resources?tabs=HTTP>
8+
///
9+
use azure_identity::DefaultAzureCredential;
10+
use azure_mgmt_resourcegraph::{
11+
models::{QueryRequest, QueryRequestOptions},
12+
Client,
13+
};
14+
use std::sync::Arc;
15+
16+
#[tokio::main]
17+
async fn main() -> azure_core::Result<()> {
18+
let azure_creds = Arc::new(DefaultAzureCredential::default());
19+
let client = Client::builder(azure_creds).build();
20+
21+
// query 10 records at a time
22+
let options = Some(QueryRequestOptions {
23+
top: Option::from(10),
24+
..Default::default()
25+
});
26+
27+
let mut query_request = QueryRequest {
28+
subscriptions: vec![],
29+
management_groups: vec![],
30+
query: "Resources | where type == 'microsoft.compute/virtualmachines'".to_string(),
31+
options,
32+
facets: vec![],
33+
};
34+
35+
loop {
36+
let response = client.resources(query_request.clone()).await?;
37+
if let Some(as_array) = response.data.as_array() {
38+
for entry in as_array {
39+
if let Some(resource_id) = entry.get("id").and_then(|x| x.as_str()) {
40+
println!("{resource_id:?}");
41+
}
42+
}
43+
}
44+
45+
// The documentation describes skip token as "Continuation token for pagination, capturing
46+
// the next page size and offset, as well as the context of the query."
47+
//
48+
// As such, if the response contains a skip_token, we use that for subsequent queries.
49+
// Otherwise, we're done.
50+
if response.skip_token.is_none() {
51+
break;
52+
}
53+
query_request.options = Some(QueryRequestOptions {
54+
skip_token: response.skip_token,
55+
..Default::default()
56+
});
57+
}
58+
Ok(())
59+
}

0 commit comments

Comments
 (0)