You can conditionally assign value to the variable in YAML pipeline.
For example, suppose there are 4 Docker registry service connections to 4 different Docker registries (Registry01
, Registry02
, Registry03
and Registry04
), and 3 branches (main
, test
and development
) in the Git repository.
The targets are:
- When the build is run for
main
branch, the Docker images need to be built and pushed to Registry01
.
- When the build is run for
test
branch, the Docker images need to be built and pushed to Registry02
.
- When the build is run for
development
branch, the Docker images need to be built and pushed to Registry03
.
- When the build is run for a pull request, the Docker images need to be built and pushed to
Registry04
.
We can configure the YAML pipeline like as below:
trigger:
branches:
include:
- main
- test
- development
variables:
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
dockerRegistryServiceConnection: 'Registry01'
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/test') }}:
dockerRegistryServiceConnection: 'Registry02'
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/development') }}:
dockerRegistryServiceConnection: 'Registry03'
${{ if contains(variables['Build.SourceBranch'], 'refs/pull/') }}:
dockerRegistryServiceConnection: 'Registry04'
stages:
- stage: Build
displayName: 'Build stage'
jobs:
- job: Build
displayName: 'Build job'
pool:
vmImage: windows-latest
steps:
- task: Docker@2
displayName: 'Build and push an image to container registry'
inputs:
command: buildAndPush
repository: $(imageRepository)
Dockerfile: $(dockerfilePath)
containerRegistry: $(dockerRegistryServiceConnection)
tags: |
$(tag)
latest
For the values of other input parameters (repository
, Dockerfile
, tags
, etc..) on the Docker task, you can use the same method to conditionally assign their values. And you also can conditionally assign the vmImage of the agent you want to use to run the build job.
For example.
variables:
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
vmImageName: 'windows-latest'
dockerRegistryServiceConnection: 'Registry01'
imageRepository: 'repository01'
dockerfilePath: 'Dockerfile01'
tag: 'tag01'
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/test') }}:
vmImageName: 'windows-2019'
dockerRegistryServiceConnection: 'Registry02'
imageRepository: 'repository02'
dockerfilePath: 'Dockerfile02'
tag: 'tag02'
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/development') }}:
vmImageName: 'ubuntu-latest'
dockerRegistryServiceConnection: 'Registry03'
imageRepository: 'repository03'
dockerfilePath: 'Dockerfile03'
tag: 'tag03'
${{ if contains(variables['Build.SourceBranch'], 'refs/pull/') }}:
vmImageName: 'macOS-latest'
dockerRegistryServiceConnection: 'Registry04'
imageRepository: 'repository04'
dockerfilePath: 'Dockerfile04'
tag: 'tag04'