PowerShell を使用した Application Insights リソースの管理

Note

Azure を操作するには、Azure Az PowerShell モジュールを使用することをお勧めします。 作業を開始するには、Azure PowerShell のインストールに関する記事を参照してください。 Az PowerShell モジュールに移行する方法については、「AzureRM から Az への Azure PowerShell の移行」を参照してください。

この記事では、Azure Resource Manager を使用して Application Insights リソースの作成と更新を自動化する方法を説明します。 たとえば、ビルド プロセスの一部として実行します。 基本的な Application Insights リソースと共に、可用性 Web テストの作成、アラートの設定、価格の詳細の設定、その他の Azure リソースの作成を行うことができます。

これらのリソースを作成する際に重要となるのが、Resource Manager の JSON テンプレートです。 基本手順は次のとおりです。

  • 既存のリソースの JSON 定義をダウンロードします。
  • 名前などの特定の値をパラメーター化します。
  • 新しいリソースを作成するたびにテンプレートを実行します。

複数のリソースをまとめてパッケージ化して、すべてを一度に作成できます。 たとえば、連続エクスポート用の可用性テスト、アラート、ストレージを含むアプリ モニターを作成できます。 パラメーター化の一部には、いくつか細かい点があります。それについては、以降で説明します。

1 回限りのセットアップ

Azure サブスクリプションで PowerShell を使用したことがない場合は、スクリプトを実行するコンピューターに Azure PowerShell モジュールをインストールします。

  1. Microsoft Web Platform Installer (v5 以上)をインストールします。
  2. Azure PowerShell をインストールして使用する

Azure Resource Manager テンプレート (ARM テンプレート) の使用に加え、Application Insights PowerShell コマンドレットの豊富なセットがあります。 これらのコマンドレットを使用すると、Application Insights リソースをプログラムで簡単に構成できます。 次のコマンドレットによって有効になる機能を使用できます。

  • Application Insights リソースの作成および削除します。
  • Application Insights リソースとそのプロパティの一覧を取得します。
  • 連続エクスポートを作成および管理します。
  • アプリケーション キーを作成および管理します。
  • 1 日の上限を設定します。
  • 価格プランの設定。

PowerShell コマンドレットを使用して Application Insights リソースを作成する

New-AzApplicationInsights コマンドレットを使用して、Azure 米国東部データセンターに新しい Application Insights リソースを作成する方法を次に示します。

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

ARM テンプレートを使用して Application Insights リソースを作成する

ARM テンプレートを使用して Application Insights リソースを作成する

ARM テンプレートを作成する

新しい .json ファイルを作成します。 この例で template1.json を呼び出してみましょう。 ファイルに、次のコンテンツをコピーします。

    {
        "$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": "eastus",
                "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')]",
                    "ImmediatePurgeDataOn30Days": "[parameters('ImmediatePurgeDataOn30Days')]"
                },
                "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')]"
                    }
                }
            }
        ]
    }

ARM テンプレートを使用して新しい Application Insights リソースを作成する

  1. PowerShell で $Connect-AzAccount を使用して Azure にサインインします。

  2. Set-AzContext "<subscription ID>" を使用して、コンテキストをサブスクリプションに設定します。

  3. 新しいデプロイを実行して、新しい Application Insights リソースを作成します。

        New-AzResourceGroupDeployment -ResourceGroupName Fabrikam `
               -TemplateFile .\template1.json `
               -appName myNewApp
    
    
    • -ResourceGroupName は、新しいリソースを作成するグループです。
    • -TemplateFile は、カスタム パラメーターの前に置く必要があります。
    • -appName は作成するリソースの名前です。

その他のパラメーターを追加できます。 テンプレートのパラメーター セクションに説明があります。

インストルメンテーション キーの取得

アプリケーション リソースを作成したら、インストルメンテーション キーが必要になります。

  1. $Connect-AzAccount を使用して Azure にサインインします。
  2. Set-AzContext "<subscription ID>" を使用して、コンテキストをサブスクリプションに設定します。
  3. その後、次を使用します。
    1. $resource = Get-AzResource -Name "<resource name>" -ResourceType "Microsoft.Insights/components"
    2. $details = Get-AzResource -ResourceId $resource.ResourceId
    3. $details.Properties.InstrumentationKey

Application Insights リソースの他の多くのプロパティの一覧を表示するには、以下を使用します。

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

その他のプロパティについては、以下のコマンドレットを使用して確認できます。

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

これらのコマンドレットのパラメーターについては、「詳細なドキュメント」を参照してください。

Note

インストルメンテーション キーのインジェストのサポートは、2025 年 3 月 31 日に終了します。 インストルメンテーション キーのインジェストは引き続き機能しますが、この機能の更新プログラムやサポートは提供されなくなります。 接続文字列に移行することで、新機能をご利用いただけます。

データ保有期間を設定する

プログラムによって Application Insights リソースのデータ保有期間を設定する次の 3 つの方法を使用することができます。

PowerShell コマンドを使用してデータ保持を設定する

Application Insights リソースのデータ保有期間を設定する一連の簡単な PowerShell コマンドを次に示します。

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

REST を使用してデータ保持を設定する

Application Insights リソースの現在のデータ保有期間を取得するには、OSS ツール ARMClient を使用します。 ARMClient の詳細については、David Ebbo および Daniel Bowbyes による記事を参照してください。 ARMClient を使用して現在の保有期間を取得する例を次に示します。

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

保有期間を設定するには、次のような PUT コマンドを使用します。

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

前のテンプレートを使用してデータ保有期間を 365 日に設定するには、次のように実行します。

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

PowerShell スクリプトを使用することによるデータ保有期間の設定

次のスクリプトは、保有期間の変更にも使用できます。 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.azure.com/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

このスクリプトを使用して次のことを行えます。

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

1 日の上限を設定する

1 日あたりの上限のプロパティを取得するには、Set-AzApplicationInsightsPricingPlan コマンドレットを使用します。

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

1 日あたりの上限のプロパティを設定するには、同じコマンドレットを使用します。 たとえば、上限を 300 GB/日に設定するには、以下のようにします。

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

ARMClient を使用して、1 日あたりの上限のパラメーターを取得および設定することもできます。 現在の値を取得するには、以下を使用します。

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

1 日あたりの上限のリセット時間を設定する

1 日あたりの上限のリセット時間を設定するには、ARMClient を使用できます。 次に、ARMClient を使用してリセット時間を新しい時間に設定する例を示します。 この例では 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':{'Cap':100,'WarningThreshold':80,'ResetTime':12}}"

料金プランを設定する

現在の料金プランを取得するには、Set-AzApplicationInsightsPricingPlan コマンドレットを使用します。

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

料金プランを設定するには、-PricingPlan を指定して、同じコマンドレットを使用します。

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

また、前の ARM テンプレートを使用して、"microsoft.insights/components" リソースと dependsOn ノードを課金リソースから省略して、既存の Application Insights リソースに対して料金プランを設定することもできます。 たとえば、GB あたりのプラン (以前は Basic プランと呼ばれていました) に設定するには、次のように実行します。

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

priceCode は次のように定義されます。

priceCode プラン
1 GB あたり (以前は Basic プランと呼ばれていました)
2 ノードごと (以前は Enterprise プランと呼ばれていました)

最後に、ARMClient を使用して、料金プランと 1 日あたりの上限のパラメーターを取得および設定できます。 現在の値を取得するには、以下を使用します。

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

これらのパラメーターはすべて、以下を使用して設定できます。

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

このコードにより、1 日あたりの上限が 200 GB/日に設定され、1 日あたりの上限のリセット時間が 12:00 UTC に構成され、上限に達したときと警告レベルに達したときに電子メールが送信されます。また、警告のしきい値が上限の 90% に設定されます。

メトリック アラートの追加

メトリック アラートの作成を自動化するには、「メトリック アラート テンプレート」に関する記事を参照してください。

可用性テストの追加

可用性テストを自動化するには、「メトリック アラート テンプレート」に関する記事を参照してください。

リソースの追加

他のリソース (任意の種類) の作成を自動化するには、サンプルを手動で作成した後、Azure Resource Manager からそのコードをパラメーター化します。

  1. Azure リソース マネージャーを開きます。 subscriptions/resourceGroups/<your resource group>/providers/Microsoft.Insights/components に移動して、目的のアプリケーション リソースに移動します。

    Screenshot that shows navigation in Azure Resource Explorer.

    コンポーネント はアプリケーションを表示するための基本的な Application Insights リソースです。 関連するアラート ルールおよび可用性 Web テストに対して別々 のリソースがあります。

  2. コンポーネントの JSON を template1.jsonの適切な場所にコピーします。

  3. 次のプロパティを削除します。

    • id
    • InstrumentationKey
    • CreationDate
    • TenantId
  4. webtestsalertrules セクションを開き、個々の項目の JSON をテンプレートにコピーします。 webtests ノードまたは alertrules ノードからコピーしないでください。 その下の項目に移動します。

    各 Web テストには、関連するアラート ルールがあるため、両方をコピーする必要があります。

  5. 各リソースに次の行を挿入します。

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

テンプレートのパラメーター化

ここでは、特定の名前をパラメーターで置き換える必要があります。 テンプレートをパラメーター化するには、一連のヘルパー関数を使用して式を記述します。

文字列の一部のみをパラメーター化することはできません。そのため、concat() を使用して、文字列を構築します。

次に、作成する代替文字列の例を示します。 それぞれの代替文字列は、複数回現れます。 作成するテンプレートには、その他のものが必要になる場合があります。 これらの例では、テンプレートの上部で定義したパラメーターと変数を使用しています。

Find 置換後の文字列
"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" (小文字) "[toLower(parameters('appName'))]"
"<WebTest Name=\"myWebTest\" ...
Url=\"http://fabrikam.com/home\" ...>"
[concat('<WebTest Name=\"',
parameters('webTestName'),
'\" ... Url=\"', parameters('Url'),
'\"...>')]"

リソース間の依存関係の設定

Azure では、厳密な順序でリソースを設定する必要があります。 次の設定を開始する前に、確実に 1 つの設定を完了するために、依存関係の行を追加します。

  • 可用性テスト リソース

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

  • 可用性テストのアラート リソース

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

次のステップ

次の自動化に関するその他の記事を参照してください。