根据名称提取 Application Insight InstrumentationKey

Extracting application insight instrumentationkey based on name

我正在尝试为需要许多不同的应用程序洞察实例的大型云服务配置一些自动化。有没有一种方法可以根据应用程序洞察名称提取检测密钥?也许通过一些管理库?

是的,有 .net 库。

首先,在您的项目中安装以下 nuget 包:

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

然后,编写一个方法,其中 return 基于应用洞察名称的检测密钥。

        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 "";

        }

测试结果: