Azure, Azure Pipelines, Bicep, DevOps, IaC

Automate Maintaining a Private Bicep Module Registry with Azure Pipelines

After using IaC (Infrastructure as Code) on multiple projects it soon becomes apparent that you are performing the same actions over and over and you might want to start sharing those actions or even standardising them. IaC frameworks like Terraform, Pulumi, etc. provide a registry for sharing modules and I wondered if Bicep had something similar, it turns out there is using ACR (Azure Container Registry).

In this post we are going to use an ACR to create a private Bicep registry for sharing modules and a build pipeline to publish modules into the ACR when new modules are added or existing ones are changed.

Objectives:

  • Trigger on changes to Bicep files in the main branch
  • Add modules to the registry only if they do not already exist
  • Publish a new version of each changed module to the registry

Automate Publishing Files

First thing that we need is a Azure Container Registry, if you don’t already have one provisioned you can create one using the Azure CLI e.g.

az group create --name devops-rg --location "UK South"
az acr create --resource-group devops-rg --name devcrdevopsuks --sku Basic

Next we will need a repository that contains the Bicep modules we want to share. This could be an existing repository or a new repository. For the purpose of this, we can create a repository with a simple structure, a single folder called modules that contain the Bicep files we want to share e.g.

Now we have an ACR and a repository we can start going through those objectives.

Trigger on changes to Bicep files in the main branch

Azure Pipeline triggers can be defined to handle this objective by adding the branch name and including the paths e.g.

trigger:
  branches:
    include:
    - main
  paths:
    include:
    - '*.bicep'

Add modules to the registry only if they do not already exist

To achieve this objective we will first need a list of what is in the registry and compare that against the modules in our repository.

Initially there will be no modules in the registry but as ones are added we will want to only return the Bicep modules. It is a good idea to prefix the modules e.g. with ‘bicep/’ when adding them as you may use the ACR for other things not just Bicep modules.

We can use the Azure CLI again to get the list from the registry and filter on the prefix e.g.

az acr repository list --name $(registryName) --query "[?contains(@, '$(modulePrefix)')]" -o tsv

Combine that with some PowerShell to compare the entries, we can then publish the modules not in the registry e.g.

$version = Get-Date -f 'yyyy-MM-dd'
$publishedModules = $(az acr repository list --name $(registryName) --query "[?contains(@, '$(modulePrefix)')]" -o tsv)
Get-ChildItem -Recurse -Path ./*.bicep | Foreach-Object {
    $filename = ($_ | Resolve-Path -Relative) -replace "^./" -replace '\..*'
    # Check if module already exists in the registry
    If (-not ($publishedModules ?? @()).Contains(("$(modulePrefix)" + $filename))) {
        Write-Host "Adding new module $filename with version $version"
        az bicep publish --file $_ --target br:$(registryName).azurecr.io/bicep/${filename}:${version}
    }
}

Note: For the version using the date provides Bicep/ARM style version numbering e.g. 2022-01-23

Publish a new version of each changed module to the registry

For this objective we need to get the list of changed files from the repository. We can use the Git command diff-tree to provide a list of changes since the last commit e.g.

git diff-tree --no-commit-id --name-only --diff-filter=ad -r $(Build.SourceVersion)

This command shows the name of the files changed without the commit id and using lowercase a and d filters instruct this to not include Add or Delete changes (for further information on diff-tree see the docs).

Following this we need to filter to just Bicep file changes and then publish those changes like before e.g.

git diff-tree --no-commit-id --name-only --diff-filter=ad -r $(Build.SourceVersion) | Where-Object {$_.EndsWith('.bicep')} | Foreach-Object {
    $moduleName = ($_ | Resolve-Path -Relative) -replace "^./" -replace '\..*'
    Write-Host "Updating module $moduleName with version $version"
    az bicep publish --file $_ --target br:$(registryName).azurecr.io/$(modulePrefix)${moduleName}:${version}
}

Now we have the full PowerShell script we can add that to the pipeline using the AzureCLI task, include an install step for Bicep and then the complete pipeline looks like this:

trigger:
  branches:
    include:
    - main
  paths:
    include:
    - '*.bicep'

pr: none

variables:
  isMain: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')]
  modulePrefix: 'bicep/'

jobs:
- job: modules
  displayName: 'Publish Bicep Modules'
  condition: eq(variables.isMain, 'true')
  pool:
    vmImage: ubuntu-latest
  steps:
  - task: AzureCLI@2
    displayName: 'Publish/Update Modules to Registry'
    inputs:
      azureSubscription: $(azureSubscription)
      scriptType: 'pscore'
      scriptLocation: inlineScript
      inlineScript: |
        az bicep install
        $version = Get-Date -f 'yyyy-MM-dd'
        $publishedModules = $(az acr repository list --name $(registryName) --query "[?contains(@, '$(modulePrefix)')]" -o tsv)
        Get-ChildItem -Recurse -Path ./*.bicep | Foreach-Object {
          $filename = ($_ | Resolve-Path -Relative) -replace "^./" -replace '\..*'
          # Check if module already exists in the registry
          If (-not ($publishedModules ?? @()).Contains(("$(modulePrefix)" + $filename))) {
            Write-Host "Adding new module $filename with version $version"
            az bicep publish --file $_ --target br:$(registryName).azurecr.io/bicep/${filename}:${version}
          }
        }

        git diff-tree --no-commit-id --name-only --diff-filter=ad -r $(Build.SourceVersion) | Where-Object {$_.EndsWith('.bicep')} | Foreach-Object {
          $moduleName = ($_ | Resolve-Path -Relative) -replace "^./" -replace '\..*'
          Write-Host "Updating module $moduleName with version $version"
          az bicep publish --file $_ --target br:$(registryName).azurecr.io/$(modulePrefix)${moduleName}:${version}
        }

Consume Registry Modules

Now we have the shared modules in the registry, how do we use them? As it turns out it’s quite simple as shown in the Microsoft docs e.g.

module storageModule 'br:devcrdevopsuks.azurecr.io/bicep/modules/storage:2022-01-23' = {

Using the registry name and the module path can make this quite long and a lot to type in every time. We can however use a Bicep config file to create an alias and include the registry and module path (see the Microsoft docs for more detail) e.g.

{
  "moduleAliases": {
    "br": {
      "DevOps": {
        "registry": "devcrdevopsuks.azurecr.io",
        "modulePath": "bicep/modules"
      }
    }
  }
}

Now the name is more concise e.g.

module storageModule 'br/DevOps:storage:2022-01-23' = {

Conclusion

I have to say I like the option of using an ACR as a Bicep registry and by automating the maintenance of adding/updating the modules it makes sharing changes very easy.

The only thing that bothered me was that (at the time of writing) Visual Studio Code does not provide intellisense on which modules are available in the registry. Hopefully this will change in the future but in the meantime this handy PowerShell script will output the information about the registry modules and available versions

$items = @()
$(az acr repository list --name devcrdevopsuks --query "[?contains(@, 'bicep/')]" -o tsv) | ForEach-Object {
    $items += [PSCustomObject]@{
        Moddule = $_
        Tags = $(az acr repository show-tags --name devcrdevopsuks --repository $_ -o tsv)
        }    
}
Write-Output $items
Azure, Azure Pipelines, DevOps

Azure Pipelines – Multistage YAML

Azure Pipelines YAML allows us to create PaC (Pipeline as Code) to build and deploy applications to multiple stages e.g. Staging, Production.

To demonstrate this process I will cover the following:

  • Build a simple web application with UI tests
  • Publish the web application to an ACR (Azure Container Registry)
  • Create an Azure Web App with IaC (Infrastructure as Code)
  • Deploy the web application container to the Azure Web App
  • Run basic UI tests on multiple stages

This article assumes that you are familiar with building YAML pipelines in Azure DevOps Pipelines.

The Web Application

For simplicity I have used the default ASP.NET Core Web Application in Visual Studio 2019 with Docker Support enabled for Linux to create the web application.

The only thing added to the default web application is a few UI tests using Selenium. You can find all the code used and the deployment files on my GitHub.

The Pipeline

After creating a new pipeline in Azure Pipelines, I need to configure the Azure and ACR connection variables in the pipeline UI.

If you need to know how to configure the ACR service connection see my previous article Configure ACR – Azure DevOps.

Build Image

Now everything is configured, I can create the initial YAML to build and push the application to an ACR.

As this will be a multistage pipeline I will create the first Stage to build and push the image.

trigger:
- master

resources:
- repo: self

variables:  
  imageRepository: 'multistagepipelines'   
  tag: '$(Build.BuildId)' 
  vmImageName: 'ubuntu-latest'
  uiTestFolder: 'uitests'

stages:
- stage: Build
  displayName: Build and push stage
  jobs:  
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)  
    steps:
      - task: Docker@2
        displayName: Build and push an image to container registry
        inputs:
          containerRegistry: 'ACR Connection'
          repository: '$(imageRepository)'
          command: 'buildAndPush'
          Dockerfile: '**/Dockerfile'
          tags: |
            latest
            $(tag)

Now I can run this pipeline and see if it was successful.

And I can check the ACR in Azure to confirm the image has successfully been created.

Define the Web App

Now I have the image uploaded to the ACR, I need to define the Azure Web App that I will be deploying to.

For this I will use an ARM (Azure Resource Manager) template.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "siteName": {
            "type": "string",
            "metadata": {
                "description": "The unique name of your Web Site."
            }
        },
        "appImageName": {
            "type": "string",
            "metadata": {
                "description": "The name of the container image for this web app"
            }
        },
        "containerRegistryName": {
            "type": "string",
            "metadata": {
                "description": "The name of the azure container registry that contains the webapp"
            }
        },
        "containerRegistryUserName": {
            "type": "string",
            "metadata": {
                "description": "The user name to access the azure container registry"
            }
        },
        "containerRegistryPassword": {
            "type": "string",
            "metadata": {
                "description": "The password to access the azure container registry"
            }
        }

    },
    "variables": {
        "hostingPlanName": "[concat('hpn-',  parameters('siteName'))]",
        "siteApiVersion": "2019-08-01"
    },
    "resources": [
        {
            "type": "Microsoft.Web/serverfarms",
            "apiVersion": "[variables('siteApiVersion')]",
            "name": "[variables('hostingPlanName')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "name": "[variables('hostingPlanName')]",
                "workerSizeId": "1",
                "reserved": true,
                "numberOfWorkers": "1"
            },
            "sku": {
                "Tier": "Standard",
                "Name": "S1"
            },
            "kind": "linux"
        },
        {
            "name": "[parameters('siteName')]",
            "type": "Microsoft.Web/sites",
            "apiVersion": "[variables('siteApiVersion')]",
            "kind": "app,linux,container",
            "location": "[resourceGroup().location]",
            "tags": {
                "hostingPlan": "[variables('hostingPlanName')]",
                "displayName": "[parameters('siteName')]"
            },
            "dependsOn": [
                "[variables('hostingPlanName')]"
            ],
            "properties": {
                "name": "[parameters('siteName')]",
                "serverFarmId": "[variables('hostingPlanName')]",
                "siteConfig": {
                    "use32BitWorkerProcess": false,
                    "http20Enabled": true,
                    "minTlsVersion": "1.2",
                    "alwaysOn": true,
                    "linuxFxVersion": "[concat('DOCKER|', parameters('appImageName'))]",
                    "appSettings": [
                        {
                            "name": "DOCKER_REGISTRY_SERVER_USERNAME",
                            "value": "[parameters('containerRegistryUserName')]"
                        },
                        {
                            "name": "DOCKER_REGISTRY_SERVER_URL",
                            "value": "[concat('https://',parameters('containerRegistryName'))]"
                        },
                        {
                            "name": "DOCKER_REGISTRY_SERVER_PASSWORD",
                            "value": "[parameters('containerRegistryPassword')]"
                        }
                    ]
                }
            }
        }
    ],
    "outputs": {}
}

There are few things to note in this template, firstly that we are deploying to a linux container so the website configuration is a little different to normal. The kind property needs to include more information than just app.

"kind": "app,linux,container"

And the reserved property must be set to true.

 "reserved": true

There are also a couple of settings that aren’t really documented in the Microsoft Docs to configure the app settings to connect to the ACR to retrieve the image. Adding these appSettings will setup the connection.

"appSettings": [
 {
   "name": "DOCKER_REGISTRY_SERVER_USERNAME",
   "value": "[parameters('containerRegistryUserName')]"
 },
 {
   "name": "DOCKER_REGISTRY_SERVER_URL",
   "value": "[concat('https://',parameters('containerRegistryName'))]"
 },
 {
   "name": "DOCKER_REGISTRY_SERVER_PASSWORD",
   "value": "[parameters('containerRegistryPassword')]"
  }
]

Publish Template

The first thing to change in the pipeline is to add a step to upload the ARM template to an artifact to use later in the deployment.

Adding a PublishBuildArtifacts task to the build steps will perform the artifact creation.

- task: PublishBuildArtifacts@1
  displayName: Publish ARM template
  inputs:
    PathtoPublish: 'deploy.json'
    ArtifactName: 'template'
    publishLocation: 'Container'

Publish Tests

You may have noticed in the pipeline that I used “Jobs” and created a single job, this could be seen as unnecessary, but now I am going to add another job that will run in parallel with the Build Job.

So I need to add some tasks to build my UI tests. I’ve also added a variable “vmWindowsImageName” as for this job I am going to use a windows image. The test project is .NET Core 3.1 so I will use the DotNetCoreCLI tasks to restore packages and build the tests.

- job: BuildTests
  displayName: Build UI Tests
  pool:
    vmImage: $(vmWindowsImageName)
  steps:
    - task: DotNetCoreCLI@2
      displayName: Restore Packages
      inputs:
        command: 'restore'
        projects: 'multistagepipelinestests/*.csproj'
    - task: DotNetCoreCLI@2
      displayName: Build Tests
      inputs:
        command: 'build'
        projects: '**/multistagepipelinestests.csproj'
        arguments: '--configuration Release -o $(Build.ArtifactStagingDirectory)/uitests'

As with the ARM template, the UI tests need publishing to use later.

- task: PublishBuildArtifacts@1
  displayName: Publish UI Tests
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)/$(uiTestFolder)'
    ArtifactName: $(uiTestFolder)
    publishLocation: 'Container'

Deployment

Now the pipeline builds and publishes the necessary artifacts to the pipeline and the ACR, I can now add a new stage to deploy the application.

This new stage uses a special job, a ‘deployment’ job and uses a strategy. The Microsoft Docs have a lot of information about different strategies, for this I will use the ‘runonce’ strategy as the other strategies are not supported here.

- stage: Staging
  displayName: Deploy to Staging
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Staging
    variables:
      siteName: staging-taz-app
      siteResourceGroup: stag-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:

With the job and strategy configured, I can now add the first step to execute the ARM template and create the Web App.

- task: AzureResourceManagerTemplateDeployment@3
    displayName: Create or Update Azure Web App
    inputs:
      deploymentScope: 'Resource Group'
      azureResourceManagerConnection: $(SubscriptionName)
      subscriptionId: $(subscriptionId)
      action: 'Create Or Update Resource Group'
      resourceGroupName: $(siteResourceGroup)
      location: $(siteLocation)
      templateLocation: 'Linked artifact'
      csmFile: '$(Pipeline.Workspace)/template/deploy.json'
      overrideParameters: '-siteName $(siteName) -appImageName $(appImageName) -containerRegistryName $(containerRegistryName) -containerRegistryUserName $(containerRegistryUserName) -containerRegistryPassword $(containerRegistryPassword)'
      deploymentMode: 'Incremental'

Once the Web App is created I can deploy the application container into the new Web App. As this is a container application I will use the AzureWebAppContainer task.

- task: AzureWebAppContainer@1
  displayName: Deploy Application
  inputs:
    azureSubscription: $(SubscriptionName)
    appName: '$(siteName)'
    containers: '$(appImageName)'

Once the app is deployed I can then run the UI tests, but first I’ll need to add a FileTranform task to make sure my settings file has the correct URL configured to run the tests against.

- task: FileTransform@2
  displayName: Configure Staging
  inputs:
    folderPath: '$(Pipeline.Workspace)'
    xmlTransformationRules: ''
    jsonTargetFiles: '**/*settings.json'

If you want to check that the settings file correctly transformed you can add a simple PowerShell task to output the file contents.

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Get-Content -Path $(Pipeline.Workspace)/$(uiTestFolder)/testsettings.json'
    pwsh: true

And now a task to run the UI tests, for this I will use the VSTest task to run and publish the test results to the Azure Pipeline UI.

- task: VSTest@2
  displayName: Run UI Tests
  inputs:
    testSelector: 'testAssemblies'
    testAssemblyVer2: |
      ***tests.dll
      !***TestAdapter.dll
      !**obj**
    searchFolder: '$(Pipeline.Workspace)/$(uiTestFolder)'
    uiTests: true
    testRunTitle: 'Basic UI Tests'

There have been a lot of changes added, so let’s see the full pipeline so far:

trigger:
- master

resources:
- repo: self

variables:  
  imageRepository: 'multistagepipelines'   
  tag: '$(Build.BuildId)' 
  vmImageName: 'ubuntu-latest'
  vmWindowsImageName: 'windows-latest'
  uiTestFolder: 'uitests'

stages:
- stage: Build
  displayName: Build and push stage
  jobs:  
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)
    steps:
      - task: Docker@2
        displayName: Build and push an image to container registry
        inputs:
          containerRegistry: 'ACR Connection'
          repository: '$(imageRepository)'
          command: 'buildAndPush'
          Dockerfile: '**/Dockerfile'
          tags: |
            latest
            $(tag)
      - task: PublishBuildArtifacts@1
        displayName: Publish ARM template
        inputs:
          PathtoPublish: 'deploy.json'
          ArtifactName: 'template'
          publishLocation: 'Container'
  - job: BuildTests
    displayName: Build UI Tests
    pool:
      vmImage: $(vmWindowsImageName)
    steps:
      - task: DotNetCoreCLI@2
        displayName: Restore Packages
        inputs:
          command: 'restore'
          projects: 'multistagepipelinestests/*.csproj'
      - task: DotNetCoreCLI@2
        displayName: Build Tests
        inputs:
          command: 'build'
          projects: '**/multistagepipelinestests.csproj'
          arguments: '--configuration Release -o $(Build.ArtifactStagingDirectory)/uitests'
      - task: PublishBuildArtifacts@1
        displayName: Publish UI Tests
        inputs:
          PathtoPublish: '$(Build.ArtifactStagingDirectory)/$(uiTestFolder)'
          ArtifactName: $(uiTestFolder)
          publishLocation: 'Container'
- stage: Staging
  displayName: Deploy to Staging
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Staging
    variables:
      siteName: staging-taz-app
      siteResourceGroup: stag-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:
          - task: AzureResourceManagerTemplateDeployment@3
            displayName: Create or Update Azure Web App
            inputs:
              deploymentScope: 'Resource Group'
              azureResourceManagerConnection: $(SubscriptionName)
              subscriptionId: $(subscriptionId)
              action: 'Create Or Update Resource Group'
              resourceGroupName: $(siteResourceGroup)
              location: $(siteLocation)
              templateLocation: 'Linked artifact'
              csmFile: '$(Pipeline.Workspace)/template/deploy.json'
              overrideParameters: '-siteName $(siteName) -appImageName $(appImageName) -containerRegistryName $(containerRegistryName) -containerRegistryUserName $(containerRegistryUserName) -containerRegistryPassword $(containerRegistryPassword)'
              deploymentMode: 'Incremental'
          - task: AzureWebAppContainer@1
            displayName: Deploy Application
            inputs:
              azureSubscription: $(SubscriptionName)
              appName: '$(siteName)'
              containers: '$(appImageName)'
          - task: FileTransform@2
            displayName: Configure Staging
            inputs:
              folderPath: '$(Pipeline.Workspace)'
              xmlTransformationRules: ''
              jsonTargetFiles: '**/*settings.json'
          - task: VSTest@2
            displayName: Run UI Tests
            inputs:
              testSelector: 'testAssemblies'
              testAssemblyVer2: |
                ***tests.dll
                !***TestAdapter.dll
                !**obj**
              searchFolder: '$(Pipeline.Workspace)/$(uiTestFolder)'
              uiTests: true
              testRunTitle: 'Basic UI Tests'

Enhance the Pipeline

Currently the pipeline:

  • Builds a web application image and uploads it to an ACR
  • Deploys an Azure Web App using an ARM Template
  • Deploys the image into the Azure Web App
  • And runs UI tests against the newly deployed application

This is great but I would guess most of us don’t just have one environment that we need to deploy to and will need at least another one and maybe a manual intervention step too.

To create another environment I could just copy and paste the ‘Staging’ stage, rename it and update the variables. Whilst this approach would work, it would introduce a maintenance overhead we don’t want.

Fortunately Azure Pipelines YAML includes Templates for variables, jobs, steps and stages to handle this.

So, I will move the steps for the ‘Staging’ deployment into a template and call it web-deploy-steps.yml. The template file will look like:

steps:
- task: AzureResourceManagerTemplateDeployment@3
  displayName: Create or Update Azure Web App
  inputs:
    deploymentScope: 'Resource Group'
    azureResourceManagerConnection: $(SubscriptionName)
    subscriptionId: $(subscriptionId)
    action: 'Create Or Update Resource Group'
    resourceGroupName: $(siteResourceGroup)
    location: $(siteLocation)
    templateLocation: 'Linked artifact'
    csmFile: '$(Pipeline.Workspace)/template/deploy.json'
    overrideParameters: '-siteName $(siteName) -appImageName $(appImageName) -containerRegistryName $(containerRegistryName) -containerRegistryUserName $(containerRegistryUserName) -containerRegistryPassword $(containerRegistryPassword)'
    deploymentMode: 'Incremental'
- task: AzureWebAppContainer@1
  displayName: Deploy Application
  inputs:
    azureSubscription: $(SubscriptionName)
    appName: '$(siteName)'
    containers: '$(appImageName)'
- task: FileTransform@2
  displayName: Configure Staging
  inputs:
    folderPath: '$(Pipeline.Workspace)'
    xmlTransformationRules: ''
    jsonTargetFiles: '**/*settings.json'
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Get-Content -Path $(Pipeline.Workspace)/$(uiTestFolder)/testsettings.json'
    pwsh: true
- task: VSTest@2
  displayName: Run UI Tests
  inputs:
    testSelector: 'testAssemblies'
    testAssemblyVer2: |
      **\*tests.dll
      !**\*TestAdapter.dll
      !**\obj\**
    searchFolder: '$(Pipeline.Workspace)/$(uiTestFolder)'
    uiTests: true
    testRunTitle: 'Basic UI Tests'

Now I can update the ‘Staging’ stage to use the new template.

- stage: Staging
  displayName: Deploy to Staging
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Staging
    variables:
      siteName: staging-taz-app
      siteResourceGroup: stag-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:
          - template: web-deploy-steps.yml

It is now easy to add another stage using the same steps. I’ll add a production stage and update the variables.

- stage: Production
  displayName: Deploy to Production
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Production
    variables:
      siteName: production-taz-app
      siteResourceGroup: prod-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:
          - template: web-deploy-steps.yml

The full pipeline with the template now looks like:

trigger:
- master

resources:
- repo: self

variables:  
  imageRepository: 'multistagepipelines'   
  tag: '$(Build.BuildId)' 
  vmImageName: 'ubuntu-latest'
  vmWindowsImageName: 'windows-latest'
  uiTestFolder: 'uitests'

stages:
- stage: Build
  displayName: Build and push stage
  jobs:  
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)  
    steps:
      - task: Docker@2
        displayName: Build and push an image to container registry
        inputs:
          containerRegistry: 'ACR Connection'
          repository: '$(imageRepository)'
          command: 'buildAndPush'
          Dockerfile: '**/Dockerfile'
          tags: |
            latest
            $(tag)
      - task: PublishBuildArtifacts@1
        displayName: Publish ARM template
        inputs:
          PathtoPublish: 'deploy.json'
          ArtifactName: 'template'
          publishLocation: 'Container'
  - job: BuildTests
    displayName: Build UI Tests
    pool:
      vmImage: $(vmWindowsImageName)
    steps:
      - task: DotNetCoreCLI@2
        displayName: Restore Packages
        inputs:
          command: 'restore'
          projects: 'multistagepipelinestests/*.csproj'
      - task: DotNetCoreCLI@2
        displayName: Build Tests
        inputs:
          command: 'build'
          projects: '**/multistagepipelinestests.csproj'
          arguments: '--configuration Release -o $(Build.ArtifactStagingDirectory)/uitests'
      - task: PublishBuildArtifacts@1
        displayName: Publish UI Tests
        inputs:
          PathtoPublish: '$(Build.ArtifactStagingDirectory)/$(uiTestFolder)'
          ArtifactName: $(uiTestFolder)
          publishLocation: 'Container'
- stage: Staging
  displayName: Deploy to Staging
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Staging
    variables:
      siteName: staging-taz-app
      siteResourceGroup: stag-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:
          - template: web-deploy-steps.yml
- stage: Production
  displayName: Deploy to Production
  jobs:
  - deployment: DeployWeb
    displayName: Deploy Web App
    pool:
     vmImage: $(vmWindowsImageName)
    environment: Production
    variables:
      siteName: production-taz-app
      siteResourceGroup: prod-taz-webapp
      siteLocation: UK South
      appImageName: $(containerRegistryName)/$(imageRepository):latest
      baseSiteUrl: 'https://$(siteName).azurewebsites.net/'
    strategy:
      runOnce:       
        deploy:
          steps:
          - template: web-deploy-steps.yml

Review Output

Now the pipeline has ran, let’s check the results.

And let’s see if the resources were deployed into Azure.

Approvals and Checks

If the stage needs a manual intervention or approval step you can configure them in Azure Pipelines, just select ‘Environments’.

Once the list of environments is displayed you can select the one you need to add approvals and checks to e.g. Production.

Selecting the 3 dots on the right hand side and then selecting ‘Approvals and checks’ will allow a variety of options to be added.

There are a number of checks that can be added, here I will just select approvals.

Approvals simply need the users or groups that can approve the stage you want to control.

There are a few more settings for approvals, how many need to approve, approval timeout, etc. but I am not going to go into detail about them.

Conclusion

Azure Pipelines YAML provides a flexible way to create build and deployment pipelines that can be source controlled. Changes can be approved, tracked and are visible to everyone instead of a change via a UI that goes unnoticed and difficult to track if there is a problem caused by a change.

Being able to control the full application deployment flow this way is very powerful and allows the whole team to understand how their application is built and deployed.