Posted on 2 Comments

Connect to Azure resources with Managed Identity – Azure Web app container example

Managed identity is the recommended way to go when you need to access resources on Azure as they eliminate the need for developers having to manage credentials by providing an identity for the Azure resource in Azure AD and using it to obtain Azure Active Directory (Azure AD) tokens.

An administrator can locate the managed identity of the resource usually under Settings tab.

When you enable the system assigned identity an object (principal ID) will be created. This is the entity that Azure uses in order to reference this resource when you assign permissions through IAM.

We will examine now how we can use the managed identity in order to get an access_token that can be used to authenticate with Azure resources. In my scenario I have created a simple container that runs powershell (mcr.microsoft.com/powershell) in order to interact with rest-api calls with the azure apis. In order to do so, I got a console on the container running on the app service through the Development tools section under advanced tools

Using the below UI you can get a console of the container.

All resources that support Azure AD authentication, and thus work with managed identity use oauth access tokens for authorization. This means we first need to get a token before we can access resources.

When managed identity is enabled on a app service a local http endpoint that can provide access tokens will be available on the app service. This local http endpoint can only be reached from code running on the app service.

You can locate the http endpoint along with the secret needed by displaying environmental variables. As I used powershell image I had a command line so I pressed

set

The variables that we need are MSI_ENDPOINT which is the same as IDENTITY_ENDPOINT and MSI_SECRET. Using those two variables we can get an access_token and use this token in order to authenticate to azure resources.

In order to interact with the API I used curl. The request URL that should be created is a concatenation of MSI_ENDPOINT and the specific resource category that you want to use (see appendix at the bottom of the article). You should also use the secret inside App service as a header.

Example

curl MSI_ENDPOINT?resource=https://management.azure.com&api-version=2017-09-1 -H "Secret: MSI_SECRET" -v

Using curl we can Identify that the requested has a 200 response code and has been performed correctly.

In order to get the output of the curl command you can use -o argument.

By saving the file as kati.txt we can verify that the access_token is saved on the file under a JSON structure.

Lets now examine how we can perform the same request using powershell. First of all we should navigate in the folder on which powershell is located and execute powershell.exe.

cd windows\system32\windowspowershell\v1.0
powershell.exe

Then we can use Invoke-WebRequest to perform an HTTP call on the same url that we described above.

$kati = Invoke-WebRequest -Uri $env:MSI_ENDPOINT"?resource=https://management.azure.com&api-version=2017-09-01" -Headers @{Secret=$env:MSI_SECRET} -UseBasicParsing | ConvertFrom-Json

You can then use the $kati.access_token in order to Authenticate your Azure API calls.

Azure Resource Manager

https://management.azure.com/
Use this when you want to manage resources. I.e. create, delete, update Azure resources. This is when you would do stuff programmatically that you would otherwise do using Azure CLI or in the portal.

Resources supporting managed identity

If you want to interact with one of the APIs for a specific type of service use the following URIs for the resource parameter.
Keyvault: https://vault.azure.net
Datalake: https://datalake.azure.net/
Azure SQL: https://database.windows.net/
Eventhub: https://eventhubs.azure.net
Service Bus: https://servicebus.azure.net
Storage blobs and queues: https://storage.azure.com/

Links:

Azure Services with managed identities support – Azure AD – Microsoft Entra | Microsoft Docs

References:

Co authored with Giannis Anastasiou @ Vivawallet

Posted on Leave a comment

Add log analytics workspace to Azure app service – Terraform

Most times you will need to store logs for your azure resources in order to troubleshoot when things do not work as expected. Diagnostic settings for an app service can be enabled from the pane under Monitoring.

Then you should configure the diagnostic settings that will point which logs should be forwarded.

You can choose from the available categories shown below.

Lets now discover how we can enable diagnostic settings for an app service using terraform.

Create a file for example diagnostic_settings.tf and apply. The below configuration will enable all diagnostic settings categories.

resource "azurerm_monitor_diagnostic_setting" "diag_settings" {
  name               = "diag-settings"
  target_resource_id = azurerm_windows_web_app.app_service1.id
  log_analytics_workspace_id = local.log_analytics_workspace_id
  
  log {
    category = "AppServiceHTTPLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

    log {
    category = "AppServiceConsoleLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

    log {
    category = "AppServiceAppLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

    log {
    category = "AppServiceAuditLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

    log {
    category = "AppServiceIPSecAuditLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

     log {
    category = "AppServicePlatformLogs"
    enabled  = true

    retention_policy {
      enabled = false
    }
  }

  metric {
    category = "AllMetrics"

    retention_policy {
      enabled = false
      days = 30
    }
  }

}

You can also perform the same using a loop and a local variable in order to minimize code and make it more readable.

Assign a new variable inside your locals.tf file.

 log_analytics_log_categories     = ["AppServiceHTTPLogs", "AppServiceConsoleLogs","AppServiceAppLogs","AppServiceAuditLogs","AppServiceIPSecAuditLogs","AppServicePlatformLogs"]

Then perform terraform apply.

resource "azurerm_monitor_diagnostic_setting" "diag_settings" {
  name               = "diag-rule"
  target_resource_id = azurerm_windows_web_app.app_service1.id
  log_analytics_workspace_id = local.log_analytics_workspace_id
  
  dynamic "log" {
    iterator = entry
    for_each = local.log_analytics_log_categories
    content {
        category = entry.value
        enabled  = true

        retention_policy {
      enabled = false
        }
    }
   
  }

  metric {
    category = "AllMetrics"

    retention_policy {
      enabled = false
      days = 30
    }
  }

}

After applying terraform all the settings will be enabled.

Posted on Leave a comment

Using slots with appservice for Continuous delivery – Azure DevOps

Azure deployment slots allow your web apps to function in different instances called slots. Slots are different environments accessed through a publically available endpoint. One app instance is always assigned to the production slot, where you can toggle between multiple app instances on demand. This could contribute to have your application always available and deploy different versions without a downtime.

In this scenario we will examine an appservice setup called gservice that has a staging slot.

This staging slot will be used to deploy the code first, then do some health checks and finally swap this slot on production. In this article I will explain only the release procedure. If you want to learn how to build an appservice check the article attached below.

In the initial setup the staging environment and also the production one are both on v1. Lets say that code is pushed on the repository and now the version of the code is v2.

The first thing to do in the deployment would be to deploy the code on staging slot. This is an important step.

The code should be always deployed to staging slot.

Then after the code deployment some health tests will follow. If everything goes as expected we will need to swap the slots.

The swap should be performed always from staging to production slot.

After those two steps on your release pipeline you will have your code published on the production app service and the staging slot will retain the previous build for failover and backup reasons.

Posted on 1 Comment

Deploy an app service (web app) using Azure DevOps

In this article I will demonstrate how one can deploy app service code on Azure through Azure DevOps. App service is a hosting provider for your applications (web app) that can be created with multiple hosting options and application specific settings.

When creating an app service you can choose from many available options like different code frameworks or even container deployments.

For my demo I wanted to deploy an asp .net core web api using .net 6 version hosted on windows app service.

My repository structure is shown below. The app service that I want to deploy is the one located under Front folder.

The pipeline code can be found below:

trigger:
– none
pool:
vmImage: windows-latest
steps:
– task: VSBuild@1
displayName: Build appservice
inputs:
solution: '$(Build.SourcesDirectory)/Front/**\*.sln'
msbuildArgs: '/p:Configuration=Debug /p:Platform="Any CPU" /p:WebPublishMethod=FileSystem /p:publishUrl="$(Build.ArtifactStagingDirectory)/build" /p:DeployOnBuild=true'
clean: true
– task: ArchiveFiles@2
displayName: create archive for app service deployment
inputs:
rootFolderOrFile: '$(Build.ArtifactStagingDirectory)\build'
includeRootFolder: false
archiveType: 'zip'
archiveFile: '$(Build.StagingDirectory)/$(Build.BuildId).zip'
replaceExistingArchive: true
– task: AzureRmWebAppDeployment@4
displayName: deploy app service
inputs:
ConnectionType: 'AzureRM'
azureSubscription: 'ServiceConnectionName'
appType: 'webApp'
WebAppName: 'AppServiceName'
packageForLinux: '$(Build.StagingDirectory)/**/*.zip'

In more detail there are three necessary steps for the deployment.

The first task will build the .NET app using VSbuild task. The build will use as parameters the deployonBuild and the webpublishmethod as filesystem in order to specify the path on which the build output will be stored.

The second task will bundle this build output to a zip file and then the third task will upload this .zip file in the app service using a service connection with the subscription. The two parameters that should be changed are azureSubscription and WebAppName which should be the app service name.

When running the pipeline, a build folder will be created as shown in the below screenshot that will host the build output.

This output will be then zipped to a file that will be uploaded to the app service.