If / Else 逻辑和自定义变量
If / Else logic and custom variables
我正在尝试使用 expressions 在我的管道中 运行 一些 if / else
逻辑。
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
我已经尝试了 variables['env']
和 variables.env
语法作为 stated here 但没有运气。
知道为什么我的实施不起作用吗?我想我可以在 if/else
语句中使用系统的 variables['Build.SourceBranchName']
,但我想了解我的代码有什么问题。
因为 $[replace(replace(variables['Build.SourceBranchName'], 'main', 'prod'), 'refs/heads/', '')]
是一个 运行时 表达式,而 displayName
在 之前 运行时计算- 当 YAML 文件编译成计划时。
这就是 Build.SourceBranchName
对您有用的原因,因为此变量在运行时之前计算。
我正在尝试使用 expressions 在我的管道中 运行 一些 if / else
逻辑。
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
我已经尝试了 variables['env']
和 variables.env
语法作为 stated here 但没有运气。
知道为什么我的实施不起作用吗?我想我可以在 if/else
语句中使用系统的 variables['Build.SourceBranchName']
,但我想了解我的代码有什么问题。
因为 $[replace(replace(variables['Build.SourceBranchName'], 'main', 'prod'), 'refs/heads/', '')]
是一个 运行时 表达式,而 displayName
在 之前 运行时计算- 当 YAML 文件编译成计划时。
这就是 Build.SourceBranchName
对您有用的原因,因为此变量在运行时之前计算。