Search code examples
azureazure-application-insightsazure-cliazure-webapps

Azure Cli How to enable Application Insights for webapp


Consider the following code. It creates an application insight, then it retrieves the instrumentationkey and assigns it to my webapp.

    az monitor app-insights component create -g $resourceGroup --app $webapp --application-type web --kind web --tags $defaultTags
    
    $instrumentationKey = az monitor app-insights component show -g $resourceGroup -a $webapp --query 'instrumentationKey' -o tsv
    az webapp config appsettings set -g $resourceGroup -n $webapp --settings APPINSIGHTS_INSTRUMENTATIONKEY=$instrumentationKey APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=$instrumentationKey

However, this does not turn on application insight for the webapp as shown in this screen capture. I cannot figure out how to turn it on from azure cli.

enter image description here


Solution

  • You need to set a couple more app settings to make it exactly like if you enabled it from the Azure Portal. I believe the second important key after the instrumentation key is ApplicationInsightsAgent_EXTENSION_VERSION.

    https://learn.microsoft.com/en-us/azure/azure-monitor/app/azure-web-apps?tabs=net#automate-monitoring

    Powershell example which you can adapt to AzureCLI:

    $app = Get-AzWebApp -ResourceGroupName "AppMonitoredRG" -Name "AppMonitoredSite" -ErrorAction Stop
    $newAppSettings = @{} # case-insensitive hash map
    $app.SiteConfig.AppSettings | %{$newAppSettings[$_.Name] = $_.Value} # preserve non Application Insights application settings.
    $newAppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] = "012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights instrumentation key
    $newAppSettings["APPLICATIONINSIGHTS_CONNECTION_STRING"] = "InstrumentationKey=012345678-abcd-ef01-2345-6789abcd"; # set the Application Insights connection string
    $newAppSettings["ApplicationInsightsAgent_EXTENSION_VERSION"] = "~2"; # enable the ApplicationInsightsAgent
    $app = Set-AzWebApp -AppSettings $newAppSettings -ResourceGroupName $app.ResourceGroup -Name $app.Name -ErrorAction Stop