In this article we will examine the power of templates for Azure DevOps pipelines. Templates let you define reusable content, logic, and parameters and function in two ways. You can insert reusable content with a template or you can use a template to control what is allowed in a pipeline.
When you build complex automation scenarios for your organizations, you will need to use stages, jobs and tasks as they would contain multiple environments and configuration settings.
You can find some of the reasons why you would need to follow this approach on my previous article
In this article we will examine a azure devops pipeline which contains stages, jobs and tasks. Those will be created inside templates and they will be called from the main pipeline. A high level view of the architecture can be found in the below picture.
My code structure is shown below. There is a folder for the appropriate templates and a main pipeline which is located in another folder and will refer the templates folder.
stage.yml
The stage.yml file will contain the template code for the stages. It has as parameter the name which will be given in the stage.
parameters: name: '' stages: - stage: ${{ parameters.name }} jobs: - template: job.yml parameters: name: ${{ parameters.name }}_build_job
job.yml
The job.yml file will contain the template code for the jobs. It has as parameter the name which will be given in the job and also a variable sign which will indicate if a task will be executed.
parameters: name: '' sign: false jobs: - job: ${{ parameters.name }} displayName: running ${{ parameters.name }} steps: - template: step.yml parameters: name: task1 - ${{ if eq(parameters.sign, 'true') }}: - script: echo sign is requested displayName: sign task
step.yml
The step.yml file will contain the template code for the steps. It has as parameter the name which will be given in the task.
parameters: name: '' steps: - script: echo ${{ parameters.name }} displayName: running ${{ parameters.name }}
main.yml
The main.yml file is the main reference of the pipeline and the one that will be called. If you need to add more stages on it, you would only have to add another -template section under the stages.
trigger: - none variables: - template: templates/vars.yml pool: vmImage: $(myagent) stages: - template: templates/stage.yml parameters: name: "App_Env1"
By executing the pipeline we can locate that we have one stage that is not visible (as it is the only one) and under this stage a job has been created for the task1 which we added on our template.
Find more about azure devops templates on my Udemy course: