How to pass parameters to Azure yaml templates?
Introduction
The previous article discussed the Azure templates, how to create them, and the benefits of using them at different levels (tasks, jobs, and stages). I don’t want to go through that again but in short, remember Azure templates are handy for reducing/avoiding writing the same steps for the same and different pipelines.
As we are creating the common template to reduce the duplicate work, so like function there is a way that we can only pass parameters to the template and it can accept the different values.
For example, I need to create a template that can accept different database names to restore through the PowerShell task so we can use the database name as the parameter to restore. We will discuss that in this article.
Adding parameters to a template
As we discussed earlier, templates are the same as the Yaml pipeline except we don’t have to mention additional details, just provide what you want to achieve whether at stage, job, or task level.
You can add parameters to the template as shown below.
# Path: templates/restoreDB.yml
parameters:
- name: dbName
type: string
- name: version
type: string
jobs:
- job: restoreDB_${{ parameters.dbName }}_${{ parameters.version }}
displayName: Restoring DB ${{ parameters.dbName }}
steps:
- powershell: |
Write-Host "Restoring DB ${{ parameters.dbName }} with Version: ${{ parameters.version }}"
In the above example, we are just mocking the restore process and not the actual restore.
Pass parameters from Pipeline
Once your template is ready for use, you can utilize Pipeline to call them as shown below.
trigger: none
pool:
vmImage: ubuntu-latest
stages:
- stage: stage1
displayName: Restore Stage
jobs:
- template: "templates/restoreDB.yml"
parameters:
dbName: DB001
version: 1.0.1
- template: "templates/restoreDB.yml"
parameters:
dbName: DB001
version: 1.0.2
- stage: stage2
displayName: Restore Stage2
jobs:
- template: "templates/restoreDB.yml"
parameters:
dbName: DB002
version: 1.0.0
You can read more about template parameters as mentioned in the article below.