Wednesday, February 26, 2025

Conditional Variable Assignment in Azure DevOps Pipelines

Azure DevOps pipeline expression functions enable the creation of powerful Azure DevOps YAML pipelines to achieve various advanced automation needs for build and deployment purposes. This blog explains how to use the if condition with pipeline variable values.

In an Azure DevOps YAML pipeline, a variable if condition can be defined as follow

iif(condition, the_value_returns_when_condition_true, the_value_returns_when_condition_false) 

This blog post explains a sample YAML pipeline with a variable condition that checks the build source branch. If the source branch is main, the fileName variable is set to production, otherwise, it is set to pre-production.

ex:

fileName${{ iif(eq(variables['Build.SourceBranchName'], 'main'), 'production', 'pre-production')}}

Once the pipeline is triggered from the main branch, the fileName variable is set to production. Later, the fileName variable is used by the 'Create a New File' task to create a file named production.






Once the pipeline is triggered from a branch other than main, the fileName variable is set to pre-production. Later, the fileName variable is used by the 'Create a New File' task to create a file named pre-production.



Find the complete pipeline below. (Link to Azure DevOps pipeline)

trigger:
  branches:
    include:
      - main
  paths:
    include:
      - pipelines/ifexpression
variables:
  fileName${{ iif(eq(variables['Build.SourceBranchName'], 'main'), 'production', 'pre-production')}}

stages:
stageStageA
  displayName'Stage A'
  jobs:
  - jobJobA
    displayName'Job A'
    steps:
    - taskPowerShell@2
      displayName'Create a New File'
      inputs:
        targetType'inline'
        script: |
          Write-Host "Create a file based on the branch $(Build.SourceBranchName)"
          
          New-Item "$(System.DefaultWorkingDirectory)\${{variables.fileName}}" -type file
          Write-Host "List down the files created based on $(Build.SourceBranchName)"
          ls



No comments:

Post a Comment