Azure Pipelines YAML Templates

Ivan (이반) Porta
The Startup

--

This article will talk about YAML templates. By using these templates, you can make your code reusable and simplify sharing code across multiple pipelines.

If you are new to CI/CD, you might be familiar with blocks of code repeated multiple times in a single pipeline or deploying applications in various environments. The problem with code duplication is that block refactors must be propagated to each duplicate. Because of this, both the chance of human error and the time required to develop the pipeline increase linearly as the number of duplicates.

Using YAML templates, you can define reusable content, logic, and parameters in separate templates that load into your pipeline at runtime. You can divide these templates into one of these four categories:

  • Stage: define a set of stages for related jobs
  • Job: define a collection of steps run by an agent
  • Step: define a linear sequence of operations for a job
  • Variable: alternative to hard coded values or variable groups

Example

Suppose you have a repository which needs to be automated through CI/CD pipelines with the following structure:

.
├── api
│ ├── dockerfile
│ ├── node_modules
│ ├── package-lock.json
│ ├── package.json
│ └── server.js
├── frontend
│ ├── dockerfile
│ ├── node_modules
│ ├── package.json
│ ├── public
│ ├── src
│ └── yarn.lock
└── pipelines
└── azure-pipelines.yml

Without using a template, you will have to add the tasks to build, test, and deploy the docker image of the Node.JS API. Then you will have to perform the same tasks for the React.JS front-end. The result will be something like this:

trigger:
- main
pool:
vmImage: 'ubuntu-latest'
stages:
- stage: Build
displayName: Build stage
jobs:
- job: Build_api
displayName: Build API
steps:
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- script: |
npm install
workingDirectory: '$(Build.Repository.LocalPath)/api'
displayName: 'npm install'
- job: Build_frontend
displayName: Build Frontend
steps:

--

--

Ivan (이반) Porta
The Startup

Microsoft Certified DevOps Engineer Expert | MCT | MCE | Public Speaker