1923

都内と業界の隅っこで生活しているエンジニアのノート

RBAC を使って Azure Monitor の Azure Storage メトリックからBLOBストレージの容量を取得

Azure Monitor から 使用しているBLOB ストレージの容量を取得してみます。今回は .NET SDK で取得しますので以下とほぼ同じです。

Azure Monitor の Azure Storage メトリック- .NET SDK でメトリックにアクセスする

上記を参考に、今回は RBAC を使って取得してみます。
といっても、.NET SDK を使用して多次元メトリック値を読み取る にあるサンプルコードの MonitorManagementClient を作ってる部分を基本的には変更するだけです。

Azure ADに登録したアプリケーションを使用する場合

        private async Task<MonitorManagementClient> AuthenticateWithReadOnlyClientAsync(string tenantId, string clientId, string secret, string subscriptionId)
        {
            var credentials = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
            var monitorClient = new MonitorManagementClient(credentials, _client, false)
            {
                SubscriptionId = subscriptionId
            };

            return monitorClient;
        }

Azure リソースのマネージド ID と RBAC を使用する場合

        private async Task<MonitorManagementClient> AuthenticateWithReadOnlyClientAsync()
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
            var credentials = new Microsoft.Rest.TokenCredentials(accessToken);
            var monitorClient = new MonitorManagementClient(credentials, _client, false);
            return monitorClient;

        }

Azure Functions で動かす場合は、全体ではこんな感じでしょうか。

Function1.cs

namespace MetricsInAzureMonitorFunction
{
    public class Function1
    {
        private readonly HttpClient _client;

        public Function1(IHttpClientFactory httpClientFactory)
        {
            _client = httpClientFactory.CreateClient();
        }

        [FunctionName("Function1")]
        public async Task Run([TimerTrigger("0 */30 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            await ReadStorageMetricValueTest(log);
        }

        private async Task ReadStorageMetricValueTest(ILogger log)
        {
            var subscriptionId = "XXXXXXXXXXXXXXXXXXX";
            var resourceGroupName = "XXXXXXXX";
            var storageAccountName = "XXXXXXXXXXXXXXXXXXXXXX";

            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/blobServices/default";

            using (var readOnlyClient = await AuthenticateWithReadOnlyClientAsync())
            {
                var startDate = DateTime.UtcNow.AddDays(-1).ToString("o");
                var endDate = DateTime.UtcNow.ToString("o");
                var timeSpan = startDate + "/" + endDate;

                var odataFilterMetrics = new ODataQuery<MetadataValue>("BlobType eq 'BlockBlob'");

                var response = readOnlyClient.Metrics.List(
                    resourceUri: resourceId,
                    timespan: timeSpan,
                    interval: TimeSpan.FromHours(1),
                    metricnames: "BlobCapacity",
                    odataQuery: odataFilterMetrics,
                    aggregation: "Average",
                    resultType: ResultType.Data);

                foreach (var d in response.Value.SelectMany(m => m.Timeseries).SelectMany(m => m.Data))
                {
                    if (d.Average == null) continue;

                    log.LogInformation($"TimeStamp={d.TimeStamp}, Average={d.Average.Value}");
                }
            }
        }
        private async Task<MonitorManagementClient> AuthenticateWithReadOnlyClientAsync()
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
            var credentials = new Microsoft.Rest.TokenCredentials(accessToken);
            var monitorClient = new MonitorManagementClient(credentials, _client, false);
            return monitorClient;
        }
    }
}

Startup.cs

[assembly: FunctionsStartup(typeof(MetricsInAzureMonitorFunction.Startup))]
namespace MetricsInAzureMonitorFunction
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
        }
    }
}

サポートされてるメトリックは以下に記載されていますので、BLOB以外にも同じような感じで取得できます。

docs.microsoft.com