January 29th, 2020

Accessing Azure Resource Consumption Data Using .NET

Developer Support
Cloud Solution Architects

App Dev Manager Kyle Johnson shares a look at tracking resource consumption with .NET.


I don’t know about you but every time I call a web service in my application, I’m nervous about going over my limit. Now I know they are ways you can protect yourself from spending too much like budgets which you can setup in the portal but I thought it would be helpful to show you how you can access your Azure resource consumption data via .NET. Having access to this data at the code level can allow ways to do other things if a budget limit is reached for a particular resource.

You need a Service Principal If you don’t already have one. You can use the Azure portal to create the Service Principal. How to: Use the portal to create an Azure AD application and service principal that can access resources

There are a few things you need:

  1. Subscription ID – The subscription id of the subscription you want to access the consumption data for
  2. Tenant ID – Tenant ID of your Service Principal.
  3. Client ID – Client ID of your Service Principal.
  4. Client Secret – Client Secret of your Service Principal.

The Tenant ID, Client ID and Client Secret are used to authenticate you.

Now that we have all the data we need, we can now get to writing some code.

I’m using the Microsoft.Rest.ServiceClientCredentials class to authenticate to Azure and obtain a credentials object.

class CustomLoginCredentials : ServiceClientCredentials
{
    //Variables
    private static string tenantId = "<Tenant ID goes here>";
    private static string clientId = "<Client ID goes here>";
    private static string clientSecret = "<Client Secret goes here>";
    private static string windowsURL = "https://login.windows.net/";
    private static string azureManagementURL = "https://management.azure.com/";


    private string AuthenticationToken { get; set; }

    public override void InitializeServiceClient<T>(ServiceClient<T> client)
    {
        var authenticationContext =
            new AuthenticationContext(windowsURL + tenantId);
        var credential = new ClientCredential(clientId, clientSecret);

        var result = authenticationContext.AcquireTokenAsync(azureManagementURL,
            clientCredential: credential).Result;

        AuthenticationToken = result.AccessToken;
    }
    public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
        await base.ProcessHttpRequestAsync(request, cancellationToken);
    }
}

Once I have a client credentials object I use the object to access the consumption data in Azure per resource in a given subscription.

private async void GetAzureResourcesConsumption()
        {
            var credentials = new CustomLoginCredentials();
            ConsumptionManagementClient client = new ConsumptionManagementClient(credentials);
            client.SubscriptionId = subscriptionId;

            var resources = await client.UsageDetails.ListAsync(null, null, null, top: NumberOfItems);
            var results = resources.ToList<UsageDetail>();
        }

For a detailed exploration of techniques to manage billing and cost management, see Prevent unexpected charges with Azure billing and cost management which details a variety of techniques to help track your Azure consumption.

Author

Developer Support
Cloud Solution Architects

Microsoft Developer Support helps software developers rapidly build and deploy quality applications for Microsoft platforms.

0 comments

Discussion are closed.