给定 Applications Insight Instrumentation 密钥,获取 Azure 中的服务名称

Given an Applications Insight Instrumentation key, get the name of the service in Azure

如何在给定检测密钥的情况下以编程方式确定 Application Insights 实例的名称?

我们公司在Azure中有大量的应用洞察实例。在对应用程序进行故障排除时,可能需要很长时间才能为特定应用程序找到正确的应用程序洞察实例。

I should have specified (more than just using C# tag), that I was looking for a C# solution. Ideally, I would like to embed something so I could implement a page like 'myapp.com/appinsights' and this would give me the correct app insights instance (of the hundreds that we have) for a given app.

您可以将 PowerShell 与 AzureRm cmdlet 结合使用来执行此操作。如果您是新手,请在此处查看 Azure Resource Manager

您首先需要使用 Login-AzureRmAccount 登录,然后 select 使用 Select-AzureRmSubscription

订阅

以下脚本将获取每个 Application Insights 实例的名称及其检测密钥的列表:

Get-AzureRmResource -ExpandProperties -ResourceType "microsoft.insights/components"  -ResourceGroupName "your-resource-group" | select -ExpandProperty Properties  | Select Name, InstrumentationKey

其工作原理如下:

  1. 从您的组
  2. 中获取所有类型为 microsoft.insight/components 的资源
  3. 展开它的属性
  4. 在属性中找到 instrumentationkey 和名称

根据@mafue 的评论,以下 powershell 命令可让您跨资源组查找检测密钥:

Import-Module -Name AzureRM
Login-AzureRmAccount
Select-AzureRmSubscription <subscription id> 

Find-AzureRmResource -ExpandProperties -ResourceType "microsoft.insights/components" | select -ExpandProperty Properties | Select Name, InstrumentationKey

较旧的 AzureRM PowerShell 模块 is being replaced 由新的跨平台 Az 模块组成。根据@tobias 和@ranieuwe 的回答,以下可以使用较新的模块获取所有 InstrumentationKeys。

安装Az模块

Install-Module -Name Az -AllowClobber 作为管理员,或

Install-Module -Name Az -AllowClobber -Scope CurrentUser 作为非管理员

完整说明在这里:https://docs.microsoft.com/en-us/powershell/azure/install-az-ps

如果需要,删除旧的 AzureRM 模块

如果您收到有关 AzAzureRM 都为 installed/loaded 的警告,您可以通过 running the following as admin 卸载旧模块:Uninstall-AzureRm

登录到 Azure 和 select 检测密钥

Import-Module Az
Connect-AzAccount
Get-AzSubscription # will list all currently connected subscriptions
Select-AzSubscription <subscription-id>

# Retrieve all Instrumentation Keys along with name of AppInsights resource
Get-AzResource -ExpandProperties -ResourceType "microsoft.insights/components" | Select -ExpandProperty Properties | Select Name, InstrumentationKey

# Find a specific Instrumentation Key
Get-AzResource -ExpandProperties -ResourceType "microsoft.insights/components" | Select -ExpandProperty Properties | Where InstrumentationKey -eq "abe66a40-c437-4af1-bfe9-4b72bd6b94a1"| Select Name, InstrumentationKey

就通过 C# 使用 Instrumentation Key 获取 App Insights 实例的名称而言,我能够拼凑出以下程序。 Azure SDK 的文档非常随意,NuGet 包仍处于预览状态。

安装 NuGet 包

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

检索 App Insights 组件

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ApplicationInsights.Management;
using Microsoft.Azure.Management.ApplicationInsights.Management.Models;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Rest;

namespace CoreConsoleApp
{
    internal class Program
    {
        private static async Task Main(string[] args)
        {
            // NOTE - see below
            var auth = new AzureServiceTokenProvider();

            const string url = "https://management.azure.com/";

            var token = await auth.GetAccessTokenAsync(url);

            var cred = new TokenCredentials(token);

            var client = new ApplicationInsightsManagementClient(cred)
            {
                SubscriptionId = "<your-subscription-id>",
            };

            var list = new List<ApplicationInsightsComponent>();

            var all = await client.Components.ListAsync();
            list.AddRange(all);

            foreach(var item in list)
            {
                Console.WriteLine($"{item.Name}: {item.InstrumentationKey}");
            }
        }
    }
}

(请注意,您需要使用 C# 7.1 或更高版本才能在您的控制台应用程序中使用 async Task Main)。

关于身份验证的注意事项: AzureServiceTokenProvider 构造函数采用可选的连接字符串来向 Azure 进行身份验证。自从我通过 Azure CLI. There are quite a few other ways to get credentials, some of which are discussed in the Java client docs.

使用 az login 以来,它对我来说没有一个。

我确信有一种更有效的方法可以使用 OData 查询来查询您想要的 InstrumentationKey,但我无法弄清楚如何进行这项工作。

Microsoft.Azure.Management.ResourceManager 包中有一个更通用的 ResourceManagementClient,可以让您执行如下操作:

var client = new Microsoft.Azure.Management.ResourceManager.ResourceManagementClient(cred) { SubscriptionId = "<your-subscription-id>" };

var query = new ODataQuery<GenericResourceFilter>(o => o.ResourceType == "microsoft.insights/components")
{
    Filter = "", // filter by Instrumentation Key here?
    Expand = "$expand=Properties",
};

using (var resp = await client.Resources.ListWithHttpMessagesAsync(query))
{
    foreach (var item in resp.Body)
    {
        Console.WriteLine($"Instance name is {item.Name}");
    }
}

最后,this project 还有其他一些可能有用的示例。

使用 azure cloud shell(或安装了 azure-cli ^2.0.64 的任何 shell):

az extension add --name application-insights
az monitor app-insights component show --output table | grep <instrumentation_key>

这将搜索您当前的订阅。您可以通过

查看您当前的订阅
az account show

可能有更奇特的方式来使用 --query 但上述方法是通用的。

使用 azure CLI 非常简单:

az monitor app-insights component show --query "[?instrumentationKey=='471b5965-ce0a-4718-9bce-dc4dbcb4255f'].[applicationId, instrumentationKey]"

或者您可以使用以下方法列出所有应用洞察实例:

az monitor app-insights component show --query "[].[applicationId, instrumentationKey]"