我正在为我的一些微服务创建管道。
为了集中化和标准化,我专门为管道创建了一个 Repo。也就是说,我有一个关于在运行时填充的变量和在编译时执行 IF 条件的问题。 以下是 yaml 示例:
管道:
trigger: none
pool: "PrivPool"
resources:
repositories:
- repository: DeployingRepo
type: git
ref: refs/heads/development
name: MyPoject/MyRepo
trigger:
branches:
include:
- staging
variables:
- template: /variables/variables.yaml
stages:
- stage: Test
jobs:
- job:
steps:
- bash: |
echo "var = $(envVar)"
变量模板示例:
variables:
- name: isMaster
value: $[eq(resources.repositories['DeployingRepo'].ref, 'refs/heads/master')]
- name: isStaging
value: $[eq(resources.repositories['DeployingRepo'].ref, 'refs/heads/staging')]
- ${{ if eq(variables.isMaster, true) }}:
- name: envVar
value: 'Production'
- ${{ elseif eq(variables.isStaging, true) }}:
- name: envVar
value: 'Staging'
- ${{ else }}:
- name: envVar
value: 'Dev'
这个例子很好地代表了我需要做的事情 有没有办法强制 IF 在运行时运行,或者有其他方法让它工作?
我认为最好的选择是使用 setvariable 日志记录命令来设置可在以下任务中使用的变量。
示例:
resources:
repositories:
- repository: DeployingRepo
type: git
name: MyPoject/MyRepo
trigger:
branches:
include:
- staging
- development
variables:
- name: branch
value: $[resources.repositories.DeployingRepo.ref]
stages:
- stage: Test
jobs:
- job:
displayName: 'Test job'
steps:
- script: |
BRANCH="$(branch)"
echo "Current branch: $BRANCH"
if [ "$BRANCH" == "refs/heads/main" ]; then
echo "##vso[task.setvariable variable=envVar]Production"
elif [ "$BRANCH" == "refs/heads/master" ]; then
echo "##vso[task.setvariable variable=envVar]Production"
elif [ "$BRANCH" == "refs/heads/staging" ]; then
echo "##vso[task.setvariable variable=envVar]Staging"
else
echo "##vso[task.setvariable variable=envVar]Dev"
fi
displayName: 'Set pipeline variable'
- script: |
echo "environment: $(envVar)"
displayName: 'Display variable'
请注意,引用变量的语法可能会发生变化,具体取决于变量是否设置为
output
以及使用它的位置(相同的作业?不同的作业?) - 有关更多详细信息,请参阅输出变量的级别。