Enable Application Insights integration with App Service Diagnostics with script or arm template

Sven Saatkamp 1 Reputation point
2020-07-27T06:31:00.267+00:00

I'd like to enable Application Insights integration with App Service Diagnostics without clicking through all ob my web apps diagnositcs pages.
Also I'd like to enable it by default for new apps created with an ARM Template.

Is there a way to enable it in a scripted way by powershell, azcli or ARM template?

Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
2,786 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
6,830 questions
{count} votes

3 answers

Sort by: Most helpful
  1. BhargaviAnnadevara-MSFT 5,446 Reputation points
    2020-07-28T04:30:17.76+00:00

    Hello @Sven Saatkamp ,

    Thanks for the question. Indeed, it is possible to automate the creation of App Insights instance and link it with your WebApp.

    In order to enable telemetry collection with Application Insights, there are a few Application settings that need to be set. These settings can be managed and configured with Azure Resource Manager templates. To fit your needs, this method can be used when deploying new App Service resources with Azure Resource Manager automation, or for modifying the settings of existing resources.

    Here is an example of one such ARM template with Application settings configured for Application Insights on GitHub.
    You could also optionally generate the ARM template by creating the resources from the Azure Portal and exporting the template using Download a template for automation option.

    App Insights can also be enabled through Powershell as described here. For Azure CLI, there is an app-insights extension that you'd need to add.

    The above information is detailed in the following docs in detail:

    0 comments No comments

  2. Duray Akar 11 Reputation points
    2021-06-16T15:54:21.293+00:00

    Hello @BhargaviAnnadevara-MSFT ,

    The CLI link you provided has nothing related to "Enable Application Insights integration with App Service" at all.
    Also, the other two links that you provided are incomplete, and does not pose any viable "Application Insights Integration".
    They do not provide any reasonable or viable means to enable/disable "Application Insights Integration" properties. For example, there are "Recommended" configurations that you can choose and configure on the portal are not provided or explained.

    Hello @Sven Saatkamp ,

    Although you can mock some application settings to partially facilitate this, unfortunately there is no "Enable Application Insights integration with App Service Diagnostics" that Microsoft provides via ARM Template, PowerShell or CLI at the time of this publishing.

    If you try to "export a template" from an existing app service that is integrated with Application Insights, you see that the "Application Insights Integration" related configurations are completely ignored from the generated template as of today.

    The option people like ourselves are left with is:

    • Configure a desired Application Insights - App Service integration
    • Go to Configuration > Application Settings > Advanced Edit for the App Service
    • Try to figure out as much as you can to get the correct Application Setting names and values that pertain to your desired Application Insights configuration
    • Use your favorite tool to transform and apply these application settings

    I think it is a shame that there is no proper programmatic way of doing this.

    I copied the relevant app settings that I could locate below for convenience.

    Hope that helps.

    Note:
    Even though you mark the Application Insight related app settings with "slotSetting"=false, these settings will not auto-magically propagate to your existing deployment slots. If you browse to the deployment slots and check Application Insights, they will show as not enabled.

    Good luck, and best regards.

    Relevant App Settings:

    [  
        {  
          "name": "APPINSIGHTS_INSTRUMENTATIONKEY",  
          "value": "<yourkey>",  
          "slotSetting": false  
        },  
        {  
          "name": "APPINSIGHTS_PROFILERFEATURE_VERSION",  
          "value": "disabled",  
          "slotSetting": false  
        },  
        {  
          "name": "APPINSIGHTS_SNAPSHOTFEATURE_VERSION",  
          "value": "disabled",  
          "slotSetting": false  
        },  
        {  
          "name": "APPLICATIONINSIGHTS_CONNECTION_STRING",  
          "value": "InstrumentationKey=<yourkey>;IngestionEndpoint=https://<yourregionprefix>.in.applicationinsights.azure.com/",  
          "slotSetting": false  
        },  
        {  
          "name": "ApplicationInsightsAgent_EXTENSION_VERSION",  
          "value": "~2",  
          "slotSetting": false  
        },  
        {  
          "name": "DiagnosticServices_EXTENSION_VERSION",  
          "value": "disabled",  
          "slotSetting": false  
        },  
        {  
          "name": "InstrumentationEngine_EXTENSION_VERSION",  
          "value": "~1",  
          "slotSetting": false  
        },  
        {  
          "name": "SnapshotDebugger_EXTENSION_VERSION",  
          "value": "disabled",  
          "slotSetting": false  
        },  
        {  
          "name": "XDT_MicrosoftApplicationInsights_BaseExtensions",  
          "value": "~1",  
          "slotSetting": false  
        },  
        {  
          "name": "XDT_MicrosoftApplicationInsights_Java",  
          "value": "1",  
          "slotSetting": false  
        },  
        {  
          "name": "XDT_MicrosoftApplicationInsights_Mode",  
          "value": "recommended",  
          "slotSetting": false  
        },  
        {  
          "name": "XDT_MicrosoftApplicationInsights_NodeJS",  
          "value": "1",  
          "slotSetting": false  
        },  
        {  
          "name": "XDT_MicrosoftApplicationInsights_PreemptSdk",  
          "value": "disabled",  
          "slotSetting": false  
        }  
      ]  
    
    0 comments No comments

  3. BhargaviAnnadevara-MSFT 5,446 Reputation points
    2021-09-15T17:32:48.28+00:00

    @Sven Saatkamp Apologies, it looks like I misunderstood your requirement earlier, limited to automating the creation of Application insights resource alone.

    I now understand that you're looking for a way to automate the integration of Application Insights with App Service Diagnostics.

    As mentioned in the referenced blog post, this is how the integration works under the hood:

    When you click Connect, an API key for your Application Insights is generated with read-only access to the telemetry and this API key along with the AppId for the Application Insights resource are stored as a hidden tag in ARM at the Azure App Service app level.

    On the App Services side, you should see a new tag created at the app level with the name hidden-related:diagnostics/applicationInsightsSettings. The AppId is stored as is, but the API Key is encrypted using an internal key, so it is kept protected and not left as clear text. Using this information, App Services Diagnostics can query the Application Insights resource and is able to merge both the experiences together.

    Here is how you can simulate the integration programmatically with a PowerShell script as done from the Azure Portal:

       # Before running this script, run the following commands from an elevated Powershell console   
       # ---------------------------------------------------------------------------------------------  
       #     Install-Module -Name PowershellGet -Repository PSGallery -Force -AllowClobber  
       #     Install-Module -Name Az.ApplicationInsights -RequiredVersion 1.0.3  
       #     Install-Module -Name Az.Resources  
         
       # IMPORTANT  
       # ==========  
       # Make sure the machine does not have any AzureRM version of commands installed. If it has run the following  
       #     Uninstall-Module -Name AzureRm -AllVersions -Force  
         
       # Both Application Insights and Azure Web App should be in same subscription  
       $subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"     
         
       # Website on which AppInsights integration should be enabled  
       $siteName = "AppServiceDiagnosticsApp"  
       $siteResourceGroup = "AppServiceDiagnostics-RG"  
         
       # AppInsights resource which should be integrated with  
       $appinsightsName = "AppServiceDiagnosticsAppAI"  
       $appinsightsResourceGroup = "AppServiceDiagnostics-RG"   
         
       Connect-AzAccount | Out-Null  
       Set-AzContext -Subscription $subscriptionId  | Out-Null  
         
       $appInsightsKeyName = "APPSERVICEDIAGNOSTICS_READONLYKEY_$siteName_" + (get-date).ticks  
       $permissions = @("ReadTelemetry")  
         
       $token = Get-AzAccessToken  
       "Got Access Token"  
         
       try  
       {  
           $newApiKey = New-AzApplicationInsightsApiKey -ResourceGroupName $appinsightsResourceGroup -Name $appinsightsName -Permissions $permissions -Description $appInsightsKeyName -ErrorAction Stop  
           $appInsights = Get-AzApplicationInsights -ResourceGroupName $appinsightsResourceGroup -Name $appinsightsName  
         
           "Got App Insights Resource"  
         
           $headers = @{  
               "Authorization"="Bearer $token";   
               "Accept"="application/json";   
               "appinsights-key"=$newApiKey.ApiKey  
           }  
         
           $keyAfterEncryption = Invoke-RestMethod -Uri https://appservice-diagnostics.azurefd.net/api/appinsights/encryptkey -Headers $headers -ContentType 'application/json' -ErrorAction Stop  
         
           "Generated Encryption Key"  
         
           $webSiteResource = Get-AzResource -Name $siteName -ResourceGroup $siteResourceGroup -ResourceType "Microsoft.Web/sites" -ErrorAction Stop  
         
           "Got Website resource"  
         
           $applicationInsightsSettingsTag = @{"ApiKey"=$keyAfterEncryption;"AppId"= $appInsights.AppId}  
           $tagValue = $applicationInsightsSettingsTag | ConvertTo-Json -Compress  
           $tags = @{"hidden-related:diagnostics/applicationInsightsSettings"= $tagValue}  
         
           "Updating Website resource tag..."  
         
           Update-AzTag -ResourceId $webSiteResource.id -Tag $tags -Operation Merge -ErrorAction Stop | Out-Null  
         
           "AppInsights Integration configured successfully!"  
       }  
       catch   
       {  
           Write-Host "An error occurred:"  
           Write-Host $_  
       }  
    

    Hope this helps. Do let us know if you have further questions.

    ----------

    If an answer is helpful, please "Accept answer" and/or "Up-Vote" which might help other community members reading this thread.

    0 comments No comments