I'm trying to run some if / else
logic in my pipelines using expressions.
trigger:
- dev
- qa
- main
- test/*
resources:
- repo: self
variables:
vmImageName: 'ubuntu-latest'
# We get rid off the 'refs/heads/' to isolate the branch name and deduce the environment we're running on.
# If running on 'main' branch, env value will be 'prod'.
env: $[replace(replace(variables['Build.SourceBranchName'], 'main', 'prod'), 'refs/heads/', '')]
stages:
- stage: Build
displayName: Build stage
jobs:
- job: Build
displayName: Build
pool:
vmImage: $(vmImageName)
steps:
- script: | # this below block works as expected
if [[ $(env) == "dev" ]] ; then
echo "dev"
elif [[ $(env) == "qa" ]] ; then
echo "qa"
elif [[ $(env) == "prod" ]] ; then
echo "prod"
else
echo "We are running on an unmanaged branch"
fi
displayName: Test 1
- script: echo "Deploying to $(env)"
${{ if in(variables['env'], 'prod', 'qa', 'dev') }}:
displayName: Deploy to a managed environment # we never get there
${{ else }}:
displayName: Deploy to an unmanaged environment # always here
I have tried both variables['env']
and variables.env
syntax as stated here but no more luck.
Any idea why my implementation doesn't work ? I think I could be using the system's variables['Build.SourceBranchName']
into that if/else
statement but I would like to understand what's wrong with my code.
CodePudding user response:
It because the $[replace(replace(variables['Build.SourceBranchName'], 'main', 'prod'), 'refs/heads/', '')]
is a runtime expression, and the displayName
is evaluated before the runtime - when the YAML file is compiled into a plan.
This is why Build.SourceBranchName
will work for you, because this variable is evaluated before the runtime.