流水线间分支名称传递与多分支触发阶段配置问题
解决方案
第一步:修改first_pipeline.yml,传递分支名称并触发主流水线
先调整触发规则,让它能捕获所有目标分支的标签推送,同时把当前分支名称传递给main_pipeline:
trigger: tags: include: - '*' branches: include: - master - dev/* - deploy/* - feature/* - hotfix/* variables: agent_pool: 'DEVAGENT' # 获取当前触发流水线的分支名称 current_branch: $(Build.SourceBranchName) pool: name: $(dev_pool) # 添加阶段,手动触发主流水线并传递分支参数 stages: - stage: TriggerMainPipeline jobs: - job: Trigger steps: - task: AzureCLI@2 inputs: azureSubscription: '<你的Azure订阅名称>' scriptType: 'bash' scriptLocation: 'inlineScript' inlineScript: | az pipelines run \ --name 'main_pipeline' \ --project '<你的项目名称>' \ --variables current_branch=$(current_branch)
如果不想用AzureCLI,也可以用专门的流水线触发任务:
trigger: tags: include: - '*' branches: include: - master - dev/* - deploy/* - feature/* - hotfix/* variables: agent_pool: 'DEVAGENT' current_branch: $(Build.SourceBranchName) pool: name: $(dev_pool) resources: pipelines: - pipeline: main_pipeline source: 'main_pipeline' project: '<你的项目名称>' trigger: none # 避免自动循环触发 stages: - stage: TriggerMain jobs: - job: Trigger steps: - task: PipelineTrigger@1 inputs: pipeline: 'main_pipeline' project: '<你的项目名称>' parameters: 'current_branch=$(current_branch)'
第二步:修改main_pipeline.yml,根据分支控制阶段运行
在主流水线中接收传递来的分支变量,通过条件判断决定哪些阶段执行:
trigger: none pr: none resources: repositories: - repository: Grand type: git name: Automotive/Grand ref: master endpoint: Grand - repository: CICD type: git name: pipelines ref: master pipelines: - pipeline: Grand source: 'Grand' project: Automotive trigger: true variables: - template: variables.yml # 声明接收从first_pipeline传递的分支变量 - name: current_branch value: ${{ variables.current_branch }} stages: - stage: DEV displayName: 'Development' # 运行条件:master分支,或dev/deploy开头的分支 condition: or(eq(variables.current_branch, 'master'), startsWith(variables.current_branch, 'dev/'), startsWith(variables.current_branch, 'deploy/')) variables: - name: environment value: ${{ variables.env_dev}} pool: name: ${{ variables.agent_dev }} jobs: - deployment: DEV displayName: 'Deploying to DEV' # 剩余代码 - stage: PRD displayName: 'Production Stage' # 运行条件:master分支,或feature/hotfix开头的分支 condition: or(eq(variables.current_branch, 'master'), startsWith(variables.current_branch, 'feature/'), startsWith(variables.current_branch, 'hotfix/')) variables: - name: environment value: ${{ variables.prd }} pool: name: ${{ variables.agent_prd }} jobs: - deployment: PRDDeploy displayName: 'Deploying to PRD' # 剩余代码
核心逻辑说明
- 分支传递:通过
$(Build.SourceBranchName)自动获取触发流水线的分支名,再通过触发任务将变量传递给主流水线。 - 阶段控制:给每个阶段添加
condition条件,根据分支名匹配规则决定是否执行:- DEV阶段:仅master、dev/*、deploy/*分支运行
- PRD阶段:仅master、feature/*、hotfix/*分支运行
- 触发范围:调整
first_pipeline的trigger规则,确保所有目标分支的标签推送都能触发流水线。
内容的提问来源于stack exchange,提问作者scrapkowe
相关产品推荐
相关产品推荐

