Skip to content

Instantly share code, notes, and snippets.

@giridharmb
Created June 10, 2023 19:55
Show Gist options
  • Select an option

  • Save giridharmb/06025f097c628e1672469a351b926f8e to your computer and use it in GitHub Desktop.

Select an option

Save giridharmb/06025f097c628e1672469a351b926f8e to your computer and use it in GitHub Desktop.
Fetch Virtual Machine Records using Resource Graph API
// Using Azure Resource Graph, fetch Virtual Machine Records
use azure_identity::{ClientSecretCredential, TokenCredentialOptions};
use std::{env, sync::Arc};
use std::any::Any;
use std::borrow::Cow;
use std::future::IntoFuture;
use std::str::FromStr;
use azure_core::{AppendToUrlQuery, ClientOptions, ExponentialRetryOptions, new_http_client, RetryOptions};
use azure_core::auth::TokenCredential;
use azure_core::headers::content_type_from_headers;
use azure_core::query_param::API_VERSION;
use azure_core::resource_manager_endpoint::AZURE_CHINA_CLOUD;
use azure_identity::authority_hosts::{AZURE_CHINA, AZURE_PUBLIC_CLOUD};
use azure_mgmt_resourcegraph::models::{QueryRequest, QueryRequestOptions, ResourceChangesRequestParameters};
use azure_mgmt_resourcegraph::Client as AzureResourceGraphClient;
use azure_core::Url;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let my_options = TokenCredentialOptions::new(AZURE_CHINA.parse().unwrap());
let client_id = "<CLIENT_ID_FOR_CHINA>";
let client_secret = "<CLIENT_SECRET_FOR_CHINA>";
let tenant_id = "<CHINA_TENANT_ID>";
let client_sec_creds = ClientSecretCredential::new(
azure_core::new_http_client(),
my_http_client,
tenant_id.parse().unwrap(),
client_id.parse().unwrap(),
client_secret.parse().unwrap(),
my_options,
);
let mut creds = Arc::new(client_sec_creds);
let exponential_retry = ExponentialRetryOptions {
initial_delay: Default::default(),
max_retries: 100,
max_total_elapsed: Default::default(),
max_delay: Default::default(),
};
let retry_options = RetryOptions::exponential(exponential_retry);
let my_az_rg_client = AzureResourceGraphClient::builder(creds).endpoint(azure_core::resource_manager_endpoint::AZURE_CHINA_CLOUD).retry(retry_options).build();
// Fetch only the first 10 records
let my_top = 10;
let my_skip = 0;
let my_query = "Resources | where type =~ 'microsoft.compute/virtualmachines'".to_string();
let query_options = QueryRequestOptions {
skip_token: None,
top: Option::from(my_top),
skip: Option::from(my_skip),
result_format: None,
allow_partial_scopes: None,
authorization_scope_filter: None,
};
let custom_query_request = QueryRequest {
subscriptions: vec![],
management_groups: vec![],
query: my_query,
options: Option::from(query_options),
facets: vec![],
};
let query_request = QueryRequest::from(custom_query_request);
let resources = my_az_rg_client.resources(query_request).await;
println!("{:#?}", resources);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment