Search code examples
c#azureazure-cost-calculation

Unable to retrieve cost details from Azure API Management


I am trying to write a code to retrieve the cost detail from the Azure Cloud using the AzureManagement libraries. However, I am stucked in the part where it retrieves the data. This is my code:

using Azure.Core;
using Azure.Identity;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Consumption;
using System;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;

namespace AzureCostReport
{
    class Program
    {
        // Replace the values below with your Azure subscription ID, tenant ID, client ID, and client secret.
        private const string subscriptionId = "*********";
        private const string tenantId = "*********";
        private const string clientId = "*********";
        private const string clientSecret = "**********";

        private static ServiceClientCredentials TokenCredentials { get; set; }

        static async Task Main(string[] args)
        {
            // Authenticate using a service principal.
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
            var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { "https://management.azure.com/.default" }));

            // Create the Azure Resource Manager client.
            //var armClient = new ResourceManagementClient(TokenCredentials);

            // Set the date range for the cost report.
            var startDate = new DateTime(2023, 3, 1);
            var endDate = new DateTime(2023, 3, 1).AddDays(1).AddSeconds(-1);

            // Create the Azure Consumption client.
            var consumptionClient = new ConsumptionManagementClient(TokenCredentials);

            // Query the Azure Consumption API for the cost report.
            var result = await consumptionClient.UsageDetails.ListAsync(
                filter: $"properties/usageStart ge '{startDate}' and properties/usageEnd le '{endDate}'",
                expand: "properties/meterDetails");


            // Group the usage details by resource group and resource name.
            var usageByResource = result
                .GroupBy(r => new { r.ResourceGroupName, r.ResourceName })
                .Select(g => new {
                    ResourceGroupName = g.Key.ResourceGroupName,
                    ResourceName = g.Key.ResourceName,
                    Cost = g.Sum(r => r.Cost.Value),
                    UsageQuantity = g.Sum(r => r.UsageQuantity.Value),
                    MeterName = g.First().MeterDetails.MeterName,
                    MeterCategory = g.First().MeterDetails.MeterCategory,
                    MeterSubCategory = g.First().MeterDetails.MeterSubCategory,
                    Unit = g.First().Unit,
                    Currency = g.First().Currency
                });

            // Print the cost report.
            Console.WriteLine($"Cost Report for {startDate.ToShortDateString()}:");
            Console.WriteLine("Resource Group\tResource Name\tMeter Category\tMeter Sub-Category\tMeter Name\tUsage Quantity\tUnit\tCurrency\tCost");
            foreach (var usage in usageByResource)
            {
                Console.WriteLine($"{usage.ResourceGroupName}\t{usage.ResourceName}\t{usage.MeterCategory}\t{usage.MeterSubCategory}\t{usage.MeterName}\t{usage.UsageQuantity}\t{usage.Unit}\t{usage.Currency}\t{usage.Cost:N2}");
            }
        }
    }
}

But I have an error in this row:

               .GroupBy(r => new { r.ResourceGroupName, r.ResourceName })

It just says: CS1061: 'UsageDetail' does not contain a definition for 'ResourceGroupName' and no accesible extension Method 'ResourceGroupName' accepting a first argument of type 'UsageDetail' could be found.

I am not quite expert in this, and this little piece of code has cost me many nights of work already (I have even tried to understand better those libraries using CHAT GPT, but unfortunately I have found that that AI is as confused as I am).

Any help regarding how to troubleshoot that error will be highly appreciated. Thanks and regards.


Solution

  • The Microsoft.Azure.Management.Resources package has been deprecated. The suggested alternative is to use Azure.ResourceManager.Consumption. Could you please check if this sample code helps ? You can try to tweak that sample depending on your requirement.