Search code examples
templatesazure-devopsconditional-statements

Azure DevOps Template - conditions


Is it possible to add some conditions to this way of using templates?

I would like to use conditions based on branches.

If branch = main or development > deploy to dev

Only if branch > main, deploy to staging

The complete Pipeline:

trigger:
  batch: true
  branches:
    include:
    - main

pool: 'On-Prem Pool'

variables:
  - group: ContainerRegistry
  - group:xyz
  - name: appName
    value: 'xyz'
  - name: dockerfilePath
    value: '**/Dockerfile'


stages:


# Build App and push to container registry

- stage: Build
  displayName: Build and push to container registry
  jobs:
  - job: Build
    displayName: Build job
    pool: 'On-Prem Pool'
    steps:
    - task: Docker@2
      displayName: Login to ACR
      inputs:
        command: login
        containerRegistry: $(registryServiceConnection)
    - task: Docker@2
      displayName: Build container image
      inputs:
        command: build
        repository: $(appName)
        dockerfile: $(dockerfilePath)
        containerRegistry: $(registryServiceConnection)
        tags: $(Build.BuildId)
    - task: Docker@2
      displayName: Push container image
      inputs:
        command: push
        repository: $(appName)
        containerRegistry: $(registryServiceConnection)
      condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest')) # Don´t push to ACR on Pull Requests




# Infrastructure

# Lint the Bicep file.
- stage: Lint
  jobs: 
  - template: pipeline-templates/lint.yml

 # Deploy to the dev environment.
- template: pipeline-templates/deploy.yml
  parameters:
    environmentType: Development
    resourceGroupName: rg-xx
    appSuffix: xyz
    costCenter: 'xyz'
    serviceConnectionName: 'SVCxx'
    dockerRegistryPassword: $(dockerRegistryPassword)
    dockerRegistryUserName: $(dockerRegistryUserName)
    containerTag: $(Build.BuildId)
    registryUrl: $(registryUrl)
    cpuCores: 0.5 
    memory: 1
    minReplicas: 0
    maxReplicas: 1



 # Deploy to the staging environment.
- template: pipeline-templates/deploy.yml
  parameters:
    environmentType: Staging
    resourceGroupName: rg-xxx-001
    appSuffix: xyz
    costCenter: 'xyz'
    serviceConnectionName: 'SVCxxx'
    dockerRegistryPassword: $(dockerRegistryPassword)
    dockerRegistryUserName: $(dockerRegistryUserName)
    containerTag: $(Build.BuildId)
    registryUrl: $(registryUrl)
    cpuCores: 0.5 
    memory: 1 
    minReplicas: 1
    maxReplicas: 2
)

And it is the last two -templates I would like to apply some conditions on.

Many thanks!


Solution

  • Yes I solved it in a similar way;

    - stage: BuildDeployProd
      displayName: Build and deploy Prod env
      jobs:
      - template: pipeline-templates/deploy.yml
          parameters:
      condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))