How to Use Templates in Azure Pipeline for Reusable CI/CD
In Azure Pipelines, use
templates to define reusable pipeline parts in separate YAML files and include them with template keyword. This helps you keep your pipelines clean and consistent by sharing common steps, jobs, or stages across multiple pipelines.Syntax
Azure Pipeline templates are YAML files that define reusable pipeline components. You include them in your main pipeline using the template keyword. You can pass parameters to customize the template behavior.
- template: Path to the template YAML file.
- parameters: Optional values to customize the template.
- steps/jobs/stages: The reusable parts defined inside the template.
yaml
jobs:
- template: template-file.yml # Path to the template
parameters:
param1: value1
param2: value2Example
This example shows a main pipeline that uses a template to run a build job. The template accepts a parameter to customize the build script.
yaml
### File: build-template.yml parameters: buildScript: 'echo Building...' jobs: - job: BuildJob steps: - script: ${{ parameters.buildScript }} displayName: 'Run build script' --- ### File: azure-pipelines.yml trigger: - main jobs: - template: build-template.yml parameters: buildScript: 'echo Custom build command running...'
Output
Starting: Run build script
Custom build command running...
Finishing: Run build script
Common Pitfalls
Common mistakes when using templates include:
- Incorrect template file path causing pipeline errors.
- Not passing required parameters, leading to template failures.
- Using unsupported expressions inside templates.
- Forgetting to use
parametersblock in the template for inputs.
Always validate your YAML and test templates independently.
yaml
### Wrong usage (missing parameters block)
# template-file.yml
jobs:
- job: TestJob
steps:
- script: echo Hello
---
# main-pipeline.yml
jobs:
- template: template-file.yml
parameters:
unusedParam: value
# This will fail because the template does not declare parameters.
### Correct usage
# template-file.yml
parameters: []
jobs:
- job: TestJob
steps:
- script: echo Hello
# Now the template accepts parameters (even if empty) and works fine.Quick Reference
| Keyword | Description |
|---|---|
| template | Includes a YAML template file into the pipeline |
| parameters | Passes values to customize the template |
| steps | Defines a sequence of commands or tasks |
| jobs | Defines a group of steps that run together |
| stages | Defines a group of jobs for logical separation |
Key Takeaways
Use
template keyword to include reusable YAML files in Azure Pipelines.Define
parameters in templates to customize behavior for different pipelines.Always verify template file paths and parameter declarations to avoid errors.
Templates help keep pipelines clean, modular, and easier to maintain.
Test templates independently before integrating into main pipelines.