Search code examples
azureazure-application-insightsazure-cloud-services

Extracting application insight instrumentationkey based on name


I'm trying to configure some automation for a large cloud service that requires many different instances of application insight. Is there a way to extract instrumentation key based on application insight name? Through some management library perhaps?


Solution

  • Yes, there is .net library for that.

    First, install the following nuget packages in your project:

    Install-Package Microsoft.Azure.Management.ApplicationInsights -IncludePrerelease
    Install-Package Microsoft.Azure.Services.AppAuthentication -IncludePrerelease
    

    Then, write a method which return the instrumentation key based on app insights name.

            static string GetIKey(string app_insights_name)
            {
                string IKey = "";
                var auth = new AzureServiceTokenProvider();
    
                const string url = "https://management.azure.com/";
    
                string token = auth.GetAccessTokenAsync(url).Result;
    
                var cred = new TokenCredentials(token);
    
                var client = new ApplicationInsightsManagementClient(cred)
                {
                    //replace with your subscription id
                    SubscriptionId = "your-subscription-id",
                };
    
                var list = new List<ApplicationInsightsComponent>();
    
                var all = client.Components.List();
                list.AddRange(all);
                foreach (var item in list)
                {
                    if (item.Name.ToLower() == app_insights_name.ToLower())
                    {
                        return item.InstrumentationKey;
                    }
    
                }
    
                //if no app insights name matches, return ""
                return "";
    
            }
    

    Test result:

    enter image description here