Azure Pipelines, Bicep, DevOps, IaC

Passing Parameters to Bicep from Azure Pipelines

In previous posts I’ve used various techniques to supply parameters to Bicep from Azure Pipelines YAML and overriding values in a parameters JSON file so I thought I would collate them in one post.

Technique #1

Using multiple template files to handle complex types and standard types separately and create a variable for each parameter that can then be used for File Transform of a parameters JSON file.

parameters:
- name: tags
  displayName: 'Tags'
  type: object
  default:
     Environment: "prod"
     Resource: "AKS"
     Project: "Demo"
 - name: clusterName
    displayName: 'Name of the AKS Cluster'
    type: string
    default: 'demo'
  - name: nodeVmSize
    displayName: 'VM Size for the Nodes'
    type: string
    default: 'Standard_D2s_V3'
    values:
      - 'Standard_D2s_V3'
      - 'Standard_DS2_v2'
      - 'Standard_D4s_V3'
      - 'Standard_DS3_v2'
      - 'Standard_DS4_v2'
      - 'Standard_D8s_v3'
  - name: nodeCount
    displayName: 'The number of nodes'
    type: number
    default: 3

- template: objectparameters.yml
  parameters:
    tags: ${{ parameters.tags }}
- template: parameters.yml
  parameters:
    clusterName: ${{ parameters.clusterName }}
    nodeVmSize: ${{ parameters.nodeVmSize }}
    nodeCount: ${{ parameters.nodeCount }}
- task: FileTransform@2
  displayName: "Transform Parameters"
  inputs:
    folderPath: '$(System.DefaultWorkingDirectory)'
    xmlTransformationRules: ''
    jsonTargetFiles: 'deploy.parameters.json'

objectParameters.yml

parameters:
  - name: tags
    type: object 
steps:
- ${{ each item in parameters }}:
  - bash: |
      value='${{ convertToJson(item.value) }}'
      echo '##vso[task.setvariable variable=parameters.${{ item.key }}.value]'$value
    displayName: "Create Variable ${{ item.key }}"

parameters.yml

parameters:
  - name: clusterName
    type: string
  - name: nodeVmSize
    type: string
  - name: nodeCount
    type: number
 
steps:
- ${{ each item in parameters }}: 
    - bash: |
        echo '##vso[task.setvariable variable=parameters.${{ item.key }}.value]${{ item.value }}'
      displayName: "Create Variable ${{ item.key }}"

Technique #2

Using a PowerShell step to read all parameters and create a variable for each parameter that can then be used for File Transform of a parameters JSON file.

parameters:
- name: tags
  displayName: 'Tags'
  type: object
  default:
     Environment: "prod"
     Resource: "AKS"
     Project: "Demo"
 - name: clusterName
    displayName: 'Name of the AKS Cluster'
    type: string
    default: 'demo'
  - name: nodeVmSize
    displayName: 'VM Size for the Nodes'
    type: string
    default: 'Standard_D2s_V3'
    values:
      - 'Standard_D2s_V3'
      - 'Standard_DS2_v2'
      - 'Standard_D4s_V3'
      - 'Standard_DS3_v2'
      - 'Standard_DS4_v2'
      - 'Standard_D8s_v3'
  - name: nodeCount
    displayName: 'The number of nodes'
    type: number
    default: 3

- ${{ each item in parameters }}:  
   - pwsh: | 
       $obj = '${{ convertToJson(item.value) }}' | ConvertFrom-Json 
       $value = ($obj | ConvertTo-Json -Compress) 
       if($obj.GetType().Name -eq "String") { 
         $value = $obj 
       }  
       Write-Host "##vso[task.setvariable variable=parameters.${{ item.key }}.value;]$value"
     displayName: "Create Variable ${{ item.key }}"

- task: FileTransform@2
  displayName: "Transform Parameters"
  inputs:
    folderPath: '$(System.DefaultWorkingDirectory)'
    xmlTransformationRules: ''
    jsonTargetFiles: 'deploy.parameters.json'

example of the PowerShell step with optional part to ignore unwanted parameters using notIn.

- ${{ each item in parameters }}:  
  - ${{ if notIn(item.key, 'myunwantedparameter') }}:
    - pwsh: | 
        $obj = '${{ convertToJson(item.value) }}' | ConvertFrom-Json 
        $value = ($obj | ConvertTo-Json -Compress) 
        if($obj.GetType().Name -eq "String") { 
          $value = $obj 
        }  
        Write-Host "##vso[task.setvariable variable=parameters.${{ item.key }}.value;]$value"
      displayName: "Create Variable ${{ item.key }}"

Technique #3

Use a template file and PowerShell to create the parameters JSON file as a whole with all the parameters. Note: Probably best used from a template file with the

createParametersFile.yml

parameters: 
- name: paramsJson 
  type: string 
- name: parameterFilePath
  type: string
  default: main.parameters.json
steps: 
- pwsh: | 
    $obj = '${{ parameters.paramsJson }}' | ConvertFrom-Json -AsHashtable 
    $header = [ordered]@{ 
      schema = "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#" 
      contentVersion = "1.0.0.0" 
      parameters = @{} 
    } 
    $valueObject = New-Object -TypeName PsObject 
    foreach ($item in $obj.GetEnumerator()) 
    {   
       $value = @{ 
         value = $item.Value 
       } 
       Add-Member -InputObject $valueObject -MemberType NoteProperty -Name $item.Name -Value $value 
    } 
    $header.parameters = $valueObject 
    Set-Content ${{ parameters.parameterFilePath }} ($header | ConvertTo-Json -Depth 10)   

Call the template:

parameters:
- name: tags
  displayName: 'Tags'
  type: object
  default:
     Environment: "prod"
     Resource: "AKS"
     Project: "Demo"
 - name: clusterName
    displayName: 'Name of the AKS Cluster'
    type: string
    default: 'demo'
  - name: nodeVmSize
    displayName: 'VM Size for the Nodes'
    type: string
    default: 'Standard_D2s_V3'
    values:
      - 'Standard_D2s_V3'
      - 'Standard_DS2_v2'
      - 'Standard_D4s_V3'
      - 'Standard_DS3_v2'
      - 'Standard_DS4_v2'
      - 'Standard_D8s_v3'
  - name: nodeCount
    displayName: 'The number of nodes'
    type: number
    default: 3

- template: createParametersFile.yml
  parameters:
     paramsJson: '${{ convertToJson(parameters) }}'
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