marcduerst.com

Azure DevOps: Retrieve Application Insights instrumentation key

Recently I had to set up Azure Application Insights instances via an Azure DevOps CI/CD pipeline using ARM templates. It was straightforward — except for retrieving the newly created instrumentation key.

The Problem

I needed the instrumentation key of the newly created AppInsights instance to store it in the application’s Azure Key Vault, where the application reads its secrets from.

I added an “Azure PowerShell” step to my pipeline to run a script with the right Azure context (subscription and resource group).

According to Microsoft’s documentation, there’s a PowerShell cmdlet called Get-AzureRmApplicationInsights that should do the job. However, this cmdlet returned no value — and no error either.

The Solution

I used three pipeline variables:

  • rg_name — the Azure Resource Group name
  • appinsights_name — the resource name of the AppInsights instance
  • appInsights_instrumentationkey — receives the instrumentation key

The following Azure PowerShell script did the trick:

Write-Host "Resource Group Name: $(rg_name)"
Write-Host "AppInsights Name: $(appinsights_name)"

$instrumentationKey = (Get-AzApplicationInsights -ResourceGroupName "$(rg_name)" -Name "$(appinsights_name)").InstrumentationKey

Write-Host "Instrumentation Key: $instrumentationKey"

Write-Host "##vso[task.setvariable variable=appInsights_instrumentationkey;]$instrumentationKey"

What’s Different

The key insight: use Get-AzApplicationInsights (the newer Az module) instead of Get-AzureRmApplicationInsights (the deprecated AzureRM module). Call it to get all properties, then access .InstrumentationKey.

The last line writes the value back to the pipeline variable appInsights_instrumentationkey using the ##vso logging command.

Putting It Together

A later step in the pipeline writes appInsights_instrumentationkey to a Key Vault, where the application picks it up at runtime.

Hope this helps!