使用 PowerShell 管理 Application Insights 资源Manage Application Insights resources using PowerShell

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

本文演示如何通过 Azure 资源管理自动创建和更新 Application Insights 资源。This article shows you how to automate the creation and update of Application Insights resources automatically by using Azure Resource Management. 例如,可能在生成过程中执行此操作。You might, for example, do so as part of a build process. 除了基本的 Application Insights 资源,还可创建可用性 Web 测试、设置警报、设置定价方案和创建其他 Azure 资源。Along with the basic Application Insights resource, you can create availability web tests, set up alerts, set the pricing scheme, and create other Azure resources.

创建这些资源的关键是用于 Azure 资源管理器 的 JSON 模板。The key to creating these resources is JSON templates for Azure Resource Manager. 基本过程如下:下载现有资源的 JSON 定义;将特定值(如名称)参数化;然后在需要新建资源时运行模板。The basic procedure is: download the JSON definitions of existing resources; parameterize certain values such as names; and then run the template whenever you want to create a new resource. 可以将多个资源打包在一起,以便一次性创建它们,例如具有可用性测试、警报和连续导出的存储的应用监视器。You can package several resources together, to create them all in one go - for example, an app monitor with availability tests, alerts, and storage for continuous export. 某些参数化有一些微妙之处,此处我们将进行介绍。There are some subtleties to some of the parameterizations, which we'll explain here.

一次性设置One-time setup

如果之前尚未将 PowerShell 与 Azure 订阅结合使用:If you haven't used PowerShell with your Azure subscription before:

在要运行脚本的计算机上安装 Azure PowerShell 模块:Install the Azure PowerShell module on the machine where you want to run the scripts:

  1. 安装 Microsoft Web 平台安装程序(v5 或更高版本)Install Microsoft Web Platform Installer (v5 or higher).
  2. 将其用于安装 Azure PowerShell。Use it to install Azure PowerShell.

除了使用资源管理器模板,还可以使用许多 Application Insights PowerShell cmdlet,以编程方式轻松地配置 Application Insights 资源。In addition to using Resource Manager templates, there is a rich set of Application Insights PowerShell cmdlets, which make it easy to configure Application Insights resources programatically. cmdlet 启用的功能包括:The capabilities enabled by the cmdlets include:

  • 创建和删除 Application Insights 资源Create and delete Application Insights resources
  • 获取 Application Insights 资源及其属性的列表Get lists of Application Insights resources and their properties
  • 创建和管理连续导出Create and manage Continuous Export
  • 创建和管理应用程序密钥Create and manage Application Keys
  • 设置每日上限Set the Daily Cap
  • 设置定价计划Set the Pricing Plan

使用 PowerShell cmdlet 创建 Application Insights 资源Create Application Insights resources using a PowerShell cmdlet

下面演示了如何使用 New-AzApplicationInsights cmdlet 在 Azure 中国北部数据中心创建新的 Application Insights 资源:Here's how to create a new Application Insights resource in the Azure China North datacenter using the New-AzApplicationInsights cmdlet:

New-AzApplicationInsights -ResourceGroupName <resource group> -Name <resource name> -location chinaeast2

使用资源管理器模板创建 Application Insights 资源Create Application Insights resources using a Resource Manager template

下面展示了如何使用资源管理器模板新建 Application Insights 资源。Here's how to create a new Application Insights resource using a Resource Manager template.

创建 Azure 资源管理器模板Create the Azure Resource Manager template

创建新的 .json 文件,在此示例中将它命名为 template1.jsonCreate a new .json file - let's call it template1.json in this example. 将此内容复制到其中:Copy this content into it:

    {
        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
            "appName": {
                "type": "string",
                "metadata": {
                    "description": "Enter the name of your Application Insights resource."
                }
            },
            "appType": {
                "type": "string",
                "defaultValue": "web",
                "allowedValues": [
                    "web",
                    "java",
                    "other"
                ],
                "metadata": {
                    "description": "Enter the type of the monitored application."
                }
            },
            "appLocation": {
                "type": "string",
                "defaultValue": "chinaeast2",
                "metadata": {
                    "description": "Enter the location of your Application Insights resource."
                }
            },
            "retentionInDays": {
                "type": "int",
                "defaultValue": 90,
                "allowedValues": [
                    30,
                    60,
                    90,
                    120,
                    180,
                    270,
                    365,
                    550,
                    730
                ],
                "metadata": {
                    "description": "Data retention in days"
                }
            },
            "ImmediatePurgeDataOn30Days": {
                "type": "bool",
                "defaultValue": false,
                "metadata": {
                    "description": "If set to true when changing retention to 30 days, older data will be immediately deleted. Use this with extreme caution. This only applies when retention is being set to 30 days."
                }
            },
            "priceCode": {
                "type": "int",
                "defaultValue": 1,
                "allowedValues": [
                    1,
                    2
                ],
                "metadata": {
                    "description": "Pricing plan: 1 = Per GB (or legacy Basic plan), 2 = Per Node (legacy Enterprise plan)"
                }
            },
            "dailyQuota": {
                "type": "int",
                "defaultValue": 100,
                "minValue": 1,
                "metadata": {
                    "description": "Enter daily quota in GB."
                }
            },
            "dailyQuotaResetTime": {
                "type": "int",
                "defaultValue": 0,
                "metadata": {
                    "description": "Enter daily quota reset hour in UTC (0 to 23). Values outside the range will get a random reset hour."
                }
            },
            "warningThreshold": {
                "type": "int",
                "defaultValue": 90,
                "minValue": 1,
                "maxValue": 100,
                "metadata": {
                    "description": "Enter the % value of daily quota after which warning mail to be sent. "
                }
            }
        },
        "variables": {
            "priceArray": [
                "Basic",
                "Application Insights Enterprise"
            ],
            "pricePlan": "[take(variables('priceArray'),parameters('priceCode'))]",
            "billingplan": "[concat(parameters('appName'),'/', variables('pricePlan')[0])]"
        },
        "resources": [
            {
                "type": "microsoft.insights/components",
                "kind": "[parameters('appType')]",
                "name": "[parameters('appName')]",
                "apiVersion": "2014-04-01",
                "location": "[parameters('appLocation')]",
                "tags": {},
                "properties": {
                    "ApplicationId": "[parameters('appName')]",
                    "retentionInDays": "[parameters('retentionInDays')]"
                },
                "dependsOn": []
            },
            {
                "name": "[variables('billingplan')]",
                "type": "microsoft.insights/components/CurrentBillingFeatures",
                "location": "[parameters('appLocation')]",
                "apiVersion": "2015-05-01",
                "dependsOn": [
                    "[resourceId('microsoft.insights/components', parameters('appName'))]"
                ],
                "properties": {
                    "CurrentBillingFeatures": "[variables('pricePlan')]",
                    "DataVolumeCap": {
                        "Cap": "[parameters('dailyQuota')]",
                        "WarningThreshold": "[parameters('warningThreshold')]",
                        "ResetTime": "[parameters('dailyQuotaResetTime')]"
                    }
                }
            }
        ]
    }

使用资源管理器模板新建 Application Insights 资源Use the Resource Manager template to create a new Application Insights resource

  1. 在 PowerShell 中,使用 $Connect-AzAccount -Environment AzureChinaCloud 登录 AzureIn PowerShell, sign in to Azure using $Connect-AzAccount -Environment AzureChinaCloud

  2. 使用 Set-AzContext "<subscription ID>" 将上下文设置为订阅Set your context to a subscription with Set-AzContext "<subscription ID>"

  3. 运行新的部署来新建 Application Insights 资源:Run a new deployment to create a new Application Insights resource:

        New-AzResourceGroupDeployment -ResourceGroupName Fabrikam `
               -TemplateFile .\template1.json `
               -appName myNewApp
    
    
    • -ResourceGroupName 是要创建新资源的组。-ResourceGroupName is the group where you want to create the new resources.
    • -TemplateFile 必须在自定义参数前出现。-TemplateFile must occur before the custom parameters.
    • -appName 是要创建的资源的名称。-appName The name of the resource to create.

可添加其他参数,并且可在模板的参数部分找到说明。You can add other parameters - you'll find their descriptions in the parameters section of the template.

获取检测密钥Get the instrumentation key

创建应用程序资源后,需使用检测密钥:After creating an application resource, you'll want the instrumentation key:

  1. $Connect-AzAccount -Environment AzureChinaCloud
  2. Set-AzContext "<subscription ID>"
  3. $resource = Get-AzResource -Name "<resource name>" -ResourceType "Microsoft.Insights/components"
  4. $details = Get-AzResource -ResourceId $resource.ResourceId
  5. $details.Properties.InstrumentationKey

若要查看 Application Insights 资源的其他多个属性的列表,请运行以下代码:To see a list of many other properties of your Application Insights resource, use:

Get-AzApplicationInsights -ResourceGroupName Fabrikam -Name FabrikamProd | Format-List

可通过以下 cmdlet 获取其他属性:Additional properties are available via the cmdlets:

  • Set-AzApplicationInsightsDailyCap
  • Set-AzApplicationInsightsPricingPlan
  • Get-AzApplicationInsightsApiKey
  • Get-AzApplicationInsightsContinuousExport

有关这些 cmdlet 的参数,请参阅详细文档Refer to the detailed documentation for the parameters for these cmdlets.

设置数据保留期Set the data retention

下面是三种以编程方式设置 Application Insights 资源的数据保留期的方法。Below are three methods to programmatically set the data retention on an Application Insights resource.

使用 PowerShell 命令设置数据保留期Setting data retention using a PowerShell commands

下面是一组简单的 PowerShell 命令,用于设置 Application Insights 资源的数据保留期:Here's a simple set of PowerShell commands to set the data retention for your Application Insights resource:

$Resource = Get-AzResource -ResourceType Microsoft.Insights/components -ResourceGroupName MyResourceGroupName -ResourceName MyResourceName
$Resource.Properties.RetentionInDays = 365
$Resource | Set-AzResource -Force

使用 REST 设置数据保留期Setting data retention using REST

若要获取 Application Insights 资源的当前数据保留期,可以使用 OSS 工具 ARMClientTo get the current data retention for your Application Insights resource, you can use the OSS tool ARMClient. (若要详细了解 ARMClient,请参阅 David EbboDaniel Bowbyes 撰写的文章。)下面的示例使用 ARMClient 获取当前的数据保留期:(Learn more about ARMClient from articles by David Ebbo and Daniel Bowbyes.) Here's an example using ARMClient, to get the current retention:

armclient GET /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName?api-version=2018-05-01-preview

若要设置数据保留期,可以使用类似 PUT 的命令:To set the retention, the command is a similar PUT:

armclient PUT /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName?api-version=2018-05-01-preview "{location: 'chinaeast2', properties: {'retentionInDays': 365}}"

若要使用上述模板将数据保留期设置为 365 天,请运行:To set the data retention to 365 days using the template above, run:

New-AzResourceGroupDeployment -ResourceGroupName "<resource group>" `
       -TemplateFile .\template1.json `
       -retentionInDays 365 `
       -appName myApp

使用 PowerShell 脚本设置数据保留期Setting data retention using a PowerShell script

以下脚本还可用于更改数据保留期。The following script can also be used to change retention. 复制此脚本,并将它另存为 Set-ApplicationInsightsRetention.ps1Copy this script to save as Set-ApplicationInsightsRetention.ps1.

Param(
    [Parameter(Mandatory = $True)]
    [string]$SubscriptionId,

    [Parameter(Mandatory = $True)]
    [string]$ResourceGroupName,

    [Parameter(Mandatory = $True)]
    [string]$Name,

    [Parameter(Mandatory = $True)]
    [string]$RetentionInDays
)
$ErrorActionPreference = 'Stop'
if (-not (Get-Module Az.Accounts)) {
    Import-Module Az.Accounts
}
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
if (-not $azProfile.Accounts.Count) {
    Write-Error "Ensure you have logged in before calling this function."    
}
$currentAzureContext = Get-AzContext
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azProfile)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId)
$UserToken = $token.AccessToken
$RequestUri = "https://management.chinacloudapi.cn/subscriptions/$($SubscriptionId)/resourceGroups/$($ResourceGroupName)/providers/Microsoft.Insights/components/$($Name)?api-version=2015-05-01"
$Headers = @{
    "Authorization"         = "Bearer $UserToken"
    "x-ms-client-tenant-id" = $currentAzureContext.Tenant.TenantId
}
## Get Component object via ARM
$GetResponse = Invoke-RestMethod -Method "GET" -Uri $RequestUri -Headers $Headers 

## Update RetentionInDays property
if($($GetResponse.properties | Get-Member "RetentionInDays"))
{
    $GetResponse.properties.RetentionInDays = $RetentionInDays
}
else
{
    $GetResponse.properties | Add-Member -Type NoteProperty -Name "RetentionInDays" -Value $RetentionInDays
}
## Upsert Component object via ARM
$PutResponse = Invoke-RestMethod -Method "PUT" -Uri "$($RequestUri)" -Headers $Headers -Body $($GetResponse | ConvertTo-Json) -ContentType "application/json"
$PutResponse

然后,可以将此脚本用作:This script can then be used as:

Set-ApplicationInsightsRetention `
        [-SubscriptionId] <String> `
        [-ResourceGroupName] <String> `
        [-Name] <String> `
        [-RetentionInDays <Int>]

设置每日上限Set the daily cap

若要获取每日上限属性,请运行 Set-AzApplicationInsightsPricingPlan cmdlet:To get the daily cap properties, use the Set-AzApplicationInsightsPricingPlan cmdlet:

Set-AzApplicationInsightsDailyCap -ResourceGroupName <resource group> -Name <resource name> | Format-List

若要设置每日上限属性,请运行相同的 cmdlet。To set the daily cap properties, use same cmdlet. 例如,要将上限设置为 300GB/天。For instance, to set the cap to 300 GB/day,

Set-AzApplicationInsightsDailyCap -ResourceGroupName <resource group> -Name <resource name> -DailyCapGB 300

也可以使用 ARMClient 来获取和设置每日上限参数。You can also use ARMClient to get and set daily cap parameters. 要获取当前值,请使用:To get the current values, use:

armclient GET /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName/CurrentBillingFeatures?api-version=2018-05-01-preview

设置每日上限重置时间Set the daily cap reset time

若要设置每日上限重置时间,可以使用 ARMClientTo set the daily cap reset time, you can use ARMClient. 下面的示例使用 ARMClient 将重置时间设置为一个新的整点(在此示例中为 12:00 UTC):Here's an example using ARMClient, to set the reset time to a new hour (in this example 12:00 UTC):

armclient PUT /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName/CurrentBillingFeatures?api-version=2018-05-01-preview "{'CurrentBillingFeatures':['Basic'],'DataVolumeCap':{'ResetTime':12}}"

设置定价计划Set the pricing plan

若要获取当前的定价计划,请运行 Set-AzApplicationInsightsPricingPlan cmdlet:To get current pricing plan, use the Set-AzApplicationInsightsPricingPlan cmdlet:

Set-AzApplicationInsightsPricingPlan -ResourceGroupName <resource group> -Name <resource name> | Format-List

若要设置定价计划,请运行指定了 -PricingPlan 的相同 cmdlet:To set the pricing plan, use same cmdlet with the -PricingPlan specified:

Set-AzApplicationInsightsPricingPlan -ResourceGroupName <resource group> -Name <resource name> -PricingPlan Basic

还可以使用上面的资源管理器模板对现有的 Application Insights 资源设置定价计划,同时从计费资源中省略“microsoft.insights/components”资源和 dependsOn 节点。You can also set the pricing plan on an existing Application Insights resource using the Resource Manager template above, omitting the "microsoft.insights/components" resource and the dependsOn node from the billing resource. 例如,若要将定价计划设置为“每 GB”计划(旧称为“基本计划”),请运行:For instance, to set it to the Per GB plan (formerly called the Basic plan), run:

        New-AzResourceGroupDeployment -ResourceGroupName "<resource group>" `
               -TemplateFile .\template1.json `
               -priceCode 1 `
               -appName myApp

priceCode 定义为:The priceCode is defined as:

价格代码priceCode planplan
11 每 GB(旧称为“基本计划”)Per GB (formerly named the Basic plan)
22 每节点(旧称为“企业计划”)Per Node (formerly name the Enterprise plan)

最后,可以使用 ARMClient 来获取和设置定价计划和每日上限参数。Finally, you can use ARMClient to get and set pricing plans and daily cap parameters. 若要获取当前值,请运行:To get the current values, use:

armclient GET /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName/CurrentBillingFeatures?api-version=2018-05-01-preview

可以运行下面的代码来设置所有这些参数:And you can set all of these parameters using:

armclient PUT /subscriptions/00000000-0000-0000-0000-00000000000/resourceGroups/MyResourceGroupName/providers/microsoft.insights/components/MyResourceName/CurrentBillingFeatures?api-version=2018-05-01-preview
"{'CurrentBillingFeatures':['Basic'],'DataVolumeCap':{'Cap':200,'ResetTime':12,'StopSendNotificationWhenHitCap':true,'WarningThreshold':90,'StopSendNotificationWhenHitThreshold':true}}"

这会将每日上限设置为 200GB/天,并将每日上限重置时间配置为 12:00 UTC,同时在达到上限和警告等级时发送电子邮件,并将警告阈值设置为上限的 90%。This will set the daily cap to 200 GB/day, configure the daily cap reset time to 12:00 UTC, send emails both when the cap is hit and the warning level is met, and set the warning threshold to 90% of the cap.

添加指标警报Add a metric alert

若要自动创建指标警报,请参阅指标警报模板一文To automate the creation of metric alerts, consult the metric alerts template article

添加可用性测试Add an availability test

若要自动执行可用性测试,请参阅指标警报模板一文。To automate availability tests, consult the metric alerts template article.

添加更多资源Add more resources

要自动创建任何其他种类的资源,请手动创建示例,并从 Azure 资源管理器中复制其代码并参数化。To automate the creation of any other resource of any kind, create an example manually, and then copy and parameterize its code from Azure Resource Manager.

  1. 打开 Azure 资源管理器Open Azure Resource Manager. 通过 subscriptions/resourceGroups/<your resource group>/providers/Microsoft.Insights/components 向下导航到应用程序资源。Navigate down through subscriptions/resourceGroups/<your resource group>/providers/Microsoft.Insights/components, to your application resource.

    在 Azure 资源浏览器中导航

    Components 是用于显示应用程序的基本 Application Insights 资源。Components are the basic Application Insights resources for displaying applications. 对关联警报规则和可用性 Web 测试都有单独的资源。There are separate resources for the associated alert rules and availability web tests.

  2. 将组件的 JSON 复制到 template1.json 中的适当位置。Copy the JSON of the component into the appropriate place in template1.json.

  3. 删除这些属性:Delete these properties:

    • id
    • InstrumentationKey
    • CreationDate
    • TenantId
  4. 打开 webtestsalertrules 部分,并将各项的 JSON 复制到模板中。Open the webtests and alertrules sections and copy the JSON for individual items into your template. (不要从 webtestsalertrules 节点复制,而是转到它们下面的项。)(Don't copy from the webtests or alertrules nodes: go into the items under them.)

    每个 Web 测试都有关联的警报规则,因此必须复制这两者。Each web test has an associated alert rule, so you have to copy both of them.

    还可以包含指标相关警报。You can also include alerts on metrics. 指标名称Metric names.

  5. 在每个资源中插入此行:Insert this line in each resource:

    "apiVersion": "2015-05-01",

参数化模板Parameterize the template

现在需要将特定名称更换为参数。Now you have to replace the specific names with parameters. 若要参数化模板,则使用一组帮助程序函数编写表达式。To parameterize a template, you write expressions using a set of helper functions.

不能仅参数化字符串的一部分,因此使用 concat() 生成字符串。You can't parameterize just part of a string, so use concat() to build strings.

下面是将要进行的替换示例。Here are examples of the substitutions you'll want to make. 每个替换有多个匹配项。There are several occurrences of each substitution. 模板中可能需要其他项。You might need others in your template. 这些示例使用已在模板顶部定义的参数和变量。These examples use the parameters and variables we defined at the top of the template.

findfind 替换项replace with
"hidden-link:/subscriptions/.../../components/MyAppName" "[concat('hidden-link:',
resourceId('microsoft.insights/components',
parameters('appName')))]"
"/subscriptions/.../../alertrules/myAlertName-myAppName-subsId", "[resourceId('Microsoft.Insights/alertrules', variables('alertRuleName'))]",
"/subscriptions/.../../webtests/myTestName-myAppName", "[resourceId('Microsoft.Insights/webtests', parameters('webTestName'))]",
"myWebTest-myAppName" "[variables(testName)]"'
"myTestName-myAppName-subsId" "[variables('alertRuleName')]"
"myAppName" "[parameters('appName')]"
"myappname"(小写)"myappname" (lower case) "[toLower(parameters('appName'))]"
"<WebTest Name=\"myWebTest\" ...
Url=\"http://fabrikam.com/home\" ...>"
[concat('<WebTest Name=\"',
parameters('webTestName'),
'\" ... Url=\"', parameters('Url'),
'\"...>')]"

设置资源之间的依赖关系Set dependencies between the resources

Azure 应严格按顺序设置资源。Azure should set up the resources in strict order. 若要确保某一设置在下一设置开始前完成,则添加依赖关系行:To make sure one setup completes before the next begins, add dependency lines:

  • 在可用性测试资源中:In the availability test resource:

    "dependsOn": ["[resourceId('Microsoft.Insights/components', parameters('appName'))]"],

  • 在可用性测试的警报资源中:In the alert resource for an availability test:

    "dependsOn": ["[resourceId('Microsoft.Insights/webtests', variables('testName'))]"],

后续步骤Next steps

其他自动化文章:Other automation articles: