我需要在 ADO 中提出拉取请求时触发管道,并且当触发的管道成功时,将处理合并(使用分支策略)。环境参数的默认值是 NONPROD,但是当管道自动触发时,我想根据目标分支选择其他环境,例如用于开发的 NFT 和用于 main 的 PROD。
我尝试使用下面的代码来设置变量,并尝试使用预定义变量 ['System.PullRequest.targetBranchName'] 的条件参数,但看起来我能够在输出中看到预期的目标分支,但条件未执行。
variables:
- name: mode
value: 'apply'
- name: environment
${{ if eq( variables['System.PullRequest.targetBranchName'], 'main' ) }} :
value: 'PROD'
${{ if eq( variables['System.PullRequest.targetBranchName'], 'develop' ) }} :
value: 'NFT'
${{ else }}:
value: 'NONPROD'
下面是我尝试检查值的阶段。
stages:
- stage: setprerequisites
displayName: "setprerequisites"
jobs:
- job: checkvariables
displayName: "check variables"
steps:
- script: |
echo "source working directory --> $(System.DefaultWorkingDirectory)"
echo "selected default environmentparameter --> ${{ parameters.environment }}"
echo "selected environment from variables --> $(environment)"
echo "target branch --> $(System.PullRequest.targetBranchName)"
echo "selected terraform mode to apply --> ${{ parameters.mode }}"
echo "terraform ${{ parameters.mode }} will be applied on $(environment) environment"
以下是输出:
提前致谢
根据预定义变量,变量
System.PullRequest.targetBranchName
在模板中不可用,因此以下内容不起作用:
${{ if eq( variables['System.PullRequest.targetBranchName'], 'main' ) }}
您必须使用宏语法
$(var)
或运行时表达式 $[variables.var]
。
设置管道输出变量并将其显示在控制台中:
trigger: none
stages:
- stage: setprerequisites
displayName: "setprerequisites"
jobs:
- job: checkvariables
displayName: "check variables"
steps:
- checkout: none
- script: |
TARGET_BRANCH='$(System.PullRequest.targetBranchName)'
if [ $TARGET_BRANCH == "main" ]; then
echo "Found branch 'main', setting the environment to PROD"
echo "##vso[task.setvariable variable=ENVIRONMENT;isOutput=true]PROD"
elif [ $TARGET_BRANCH == "develop" ]; then
echo "Found branch 'develop', setting the environment to NFT"
echo "##vso[task.setvariable variable=ENVIRONMENT;isOutput=true]NFT"
else
echo "Couldn't find branches 'main' nor 'develop'. Setting the environment to NONPROD"
echo "##vso[task.setvariable variable=ENVIRONMENT;isOutput=true]NONPROD"
fi
displayName: "Set environment"
name: SetEnvironment
env:
TARGET_BRANCH: $(System.PullRequest.targetBranchName)
- script: |
echo "selected environment from variables --> $(SetEnvironment.environment)"
displayName: Check variables
请注意,
$(SetEnvironment.environment)
是在同一作业中的其他任务中使用输出变量的正确语法。
要了解如何在不同的作业/阶段中使用变量,请参阅输出变量的级别。