如何通过ARM模板创建用于批注的Application Insights API密钥
很遗憾,目前ARM模板并不支持直接创建Application Insights的API密钥。你尝试的配置里用到的apikeys子资源类型,并没有被Azure Resource Manager的官方资源定义所支持——ARM的资源提供者Microsoft.Insights并没有把API密钥作为可直接部署的资源类型暴露出来,所以你的模板部署会失败。
为什么你的尝试没成功?
你写的ARM片段中,type: apikeys这个子资源不属于Microsoft.Insights/components的官方可部署子资源范畴,ARM部署引擎无法识别这个资源类型,自然无法完成创建操作。
可行的替代方案
既然你需要在资源部署过程中自动生成用于发布批注的API密钥,推荐以下两种自动化方案:
1. 在ARM模板中嵌入部署脚本(Deployment Scripts)
可以通过ARM的Microsoft.Resources/deploymentScripts资源,在Application Insights部署完成后自动执行PowerShell命令创建API密钥,把整个流程整合在一个ARM部署中。示例模板如下:
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "variables": { "applicationInsightsName": "your-ai-resource-name", "apiKeyName": "Azure Devops Release Annotations" }, "resources": [ { "name": "[variables('applicationInsightsName')]", "type": "Microsoft.Insights/components", "location": "[resourceGroup().location]", "apiVersion": "2020-02-02-preview", "tags": { "displayName": "[concat('Component ', variables('applicationInsightsName'))]" }, "properties": { "ApplicationId": "[variables('applicationInsightsName')]", "Application_Type": "web" } }, { "type": "Microsoft.Resources/deploymentScripts", "apiVersion": "2020-10-01", "name": "GenerateAIAnnotationApiKey", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Insights/components', variables('applicationInsightsName'))]" ], "kind": "AzurePowerShell", "properties": { "azPowerShellVersion": "7.2", "scriptContent": " $aiResourceId = '[resourceId('Microsoft.Insights/components', variables('applicationInsightsName'))]' $apiKey = New-AzApplicationInsightsApiKey -ResourceId $aiResourceId -Name '[variables('apiKeyName')]' -Permissions 'WriteAnnotations' # 将密钥输出为部署结果,也可添加逻辑存入Key Vault Write-Output $apiKey.ApiKey ", "cleanupPreference": "OnSuccess", "retentionInterval": "PT1H" } } ], "outputs": { "annotationApiKey": { "type": "string", "value": "[reference('GenerateAIAnnotationApiKey').outputs.text]" } } }
这个方案的优势是:
- 整个流程完全自动化,无需手动干预
- 可以把生成的API密钥作为部署输出返回,或者直接存入Azure Key Vault(只需在脚本中添加
Set-AzKeyVaultSecret相关逻辑),安全地供Azure DevOps使用
2. 在Azure DevOps Pipeline中添加后续步骤
如果你的ARM模板部署是在Azure DevOps管道中执行的,可以在ARM部署任务之后添加一个Azure PowerShell任务,调用New-AzApplicationInsightsApiKey命令创建密钥,然后将密钥保存为管道变量,供后续的发布批注任务使用。示例PowerShell代码:
$aiResourceId = $(az resource show -g $(ResourceGroupName) -n $(ApplicationInsightsName) --resource-type Microsoft.Insights/components --query id -o tsv) $apiKey = New-AzApplicationInsightsApiKey -ResourceId $aiResourceId -Name "Azure Devops Release Annotations" -Permissions "WriteAnnotations" # 将密钥设置为管道变量 Write-Host "##vso[task.setvariable variable=AIAnnotationApiKey;issecret=true]$($apiKey.ApiKey)"
这种方案更灵活,适合已经在使用Azure DevOps进行部署的场景,而且可以直接把密钥标记为保密变量,避免泄露。
总结
虽然ARM模板无法直接创建Application Insights API密钥,但通过部署脚本或者Azure DevOps管道的后续步骤,完全可以实现你需要的自动化生成密钥的需求,满足Azure DevOps发布批注的功能。
内容的提问来源于stack exchange,提问作者honk

