This article demonstrates how to retrieve metadata of an instance in Azure using REST API Call in .NET.
Here, we will retrieve Azure VM metadata details, and also, we will list the resources as part of resource group using REST API.
The assumption here is that we already created some of the resources in resource group. In my case, Resource group contains,
- Azure VM
- App Service
- Storage Account
Before making a REST API call from .NET code for an Azure instance, we need to grant the necessary permissions by assigning the appropriate role to the service principal at the appropriate scope. The role that is required to list the metadata of an Azure App Service is the "Reader" role. Otherwise, authentication to the Azure Resource Manager (ARM) API will fail due to permissions issue to perform the "list" action on the "metadata" resource.
Points to remember, before doing a REST API call,
- Azure resources like Azure VM are already created.
- Register an app with a name in Azure Active Directory using “App Registrations”. Once that is done, create a client secret. This is required to access the resources in Azure via API Call.
- Grant role assignment to service principle created in Azure AD as part of App Registration.
Step 1 - Register App in Azure Active Directory
Go to Azure Active Directory => App Registrations => New registration
Detailed steps of the app registration process can be found here
Step 2 - IAM role assignment to service principal
Here are the steps you can use to assign the "Reader" role at the resource level using the Azure Portal:
- Select the Azure resource for which you want to grant permissions let’s say Azure VM.
- Click on Access control (IAM)
- Click on +Add to add a new role assignment
- In the Add role assignment pane, select the "Reader" role from the Role drop-down list.
- In the Assign access to drop-down list, select "Azure AD user, group, or service principal".
- In the Select section, search and select the user or service principal that you want to grant permissions.
- Click on Save to create the role assignment.
It can take a few minutes for the changes to take effect. After that, the user or service principal should have the necessary permissions to perform the "list" action on the "metadata" resource.
Step 3 - REST API call from .NET to get Azure VM Instance Metadata
NuGet packages to install,
<PackageReference Include="Microsoft.Identity.Client" Version="4.49.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
C# Code for generating token and doing REST API call,
string tenantId = "{azure-tenantId}";
string clientId = "{clientId}";
string clientSecret = "{client secret of registered app}";
string subscriptionId = "{azure-subscriptionId}";
string resourceGroupName = "{azure-resourceGroupName}";
string vmName = "{azure-vm-name}";
var app = ConfidentialClientApplicationBuilder.Create(clientId).WithClientSecret(clientSecret).WithTenantId(tenantId).Build();
var authResult = await app.AcquireTokenForClient(new string[] {
"https://management.azure.com/.default"
}).ExecuteAsync();
// Use the access token to authenticate the API call
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
// API Call to Get VM Details
// https://learn.microsoft.com/en-us/rest/api/compute/virtual-machines/get?tabs=HTTP
var response = await httpClient.GetAsync($ "https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}?api-version=2022-08-01");
if (response.IsSuccessStatusCode) {
// Retrieve the response content as a JSON string
var jsonString = await response.Content.ReadAsStringAsync();
Console.WriteLine("-------------------Get VM Details--------------------------");
Console.WriteLine(JObject.Parse(jsonString));
} else {
throw new Exception($ "Failed to retrieve VM metadata: {response.StatusCode} - {response.ReasonPhrase}");
}
Output JSON metadata of Azure VM instance in console,
REST API details of Get All Resouces in a Resouce Group,
// API call to Get Resources
var response = await httpClient.GetAsync($ "https://management.azure.com/subscriptions/{subscriptionId}/resources?api-version=2021-04-01");
if (response.IsSuccessStatusCode) {
// Retrieve the response content as a JSON string
var jsonString = await response.Content.ReadAsStringAsync();
Console.WriteLine("---------------------Get Resources---------------------------");
Console.WriteLine(JObject.Parse(jsonString));
} else {
throw new Exception($ "Failed to retrieve Resources metadata: {response.StatusCode} - {response.ReasonPhrase}");
}
Output JSON metadata of Azure resources in the console,
Happy Learning!