考虑下面的代码:
parameters:
- name: containerRegistry
displayName: Azure Container Registry Service Connection
type: string
default: 'acr-amaest'
values:
- acr-amaest
- name: deploymentSteps
type: stepList
default:
- script: echo "Add your deployment steps to your template"
displayName: Empty deployment step
- name: branchMapping
type: object
default:
develop: build
staging: staging
main: release
variables:
- name: environment
${{ each branch in parameters.branchMapping }}:
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/${{ branch.Key }}') }}:
value: ${{ branch.Value }}
stages:
- stage: Test
displayName: 🚀 Test
jobs:
- job:
steps:
# Printing empty string
- bash: |
echo ${{ variables['environment'] }}
# Works, prints everything
- ${{ each branch in parameters.branchMapping }}:
- bash: echo '${{ branch.Key }} -> ${{ branch.Value }} against ${{ variables['Build.SourceBranch'] }}'
# Prints nothing
- ${{ each branch in parameters.branchMapping }}:
- ${{ if eq(variables['Build.SourceBranchName'], '/${{ branch.Key }}') }}:
- bash: echo "Coucou ${{ branch.Key }}"
你能帮忙吗?
为了根据所选分支设置名为
environment
的变量,您可以执行以下操作:
parameters:
# other parameters here
- name: branchMapping
type: object
default:
develop: build_environment
staging: staging_environment
main: release_environment
trigger: none
pool:
vmImage: 'ubuntu-latest'
variables:
- name: sourceBranch
value: $(Build.SourceBranchName)
- name: environment
${{ each branch in parameters.branchMapping }}:
${{ if eq(variables['Build.SourceBranchName'], branch.Key) }}:
value: ${{ branch.Value }}
stages:
- stage: Test
displayName: 🚀 Test
jobs:
- job: printVariables
displayName: 'Print variables'
steps:
- checkout: none
- bash: |
echo "sourceBranch: ${{ variables.sourceBranch }}"
echo "environment: ${{ variables.environment }}"
displayName: 'Print variables'
- bash: |
echo "sourceBranch: $(sourceBranch)"
echo "environment: $(environment)"
displayName: 'Print variables using macro syntax'
从
staging
分支运行管道: