如何在Azure DevOps中复用单个容器执行顺序阶段/作业/任务/步骤?
Azure DevOps YAML流水线:让多阶段操作在同一容器中顺序执行
问题描述
现有Azure DevOps YAML流水线结构如下,各Stage会顺序执行,但每个Stage都会新建容器。需求是让这些顺序操作在同一个容器中完成,需满足两个要求:
- 所有操作按顺序执行
- 全程使用同一个容器环境
原始流水线代码:
- stage: build jobs: - job: build_main pool: type: linux # read more about custom job pool types at https://aka.ms/obpipelines/yaml/jobs variables: ob_outputDirectory: '$(REPOROOT)\out' ob_sdl_binskim_break: true steps: - task: Bash@3 displayName: "Install conda/python3.10, unixodbc, pytest and requirements" inputs: targetType: 'inline' workingDirectory: $(FRAMEWORK_DIR) script: | make setup-python-in-ubuntu make setup-local - stage: test dependsOn: build jobs: - job: test_main pool: type: linux # read more about custom job pool types at https://aka.ms/obpipelines/yaml/jobs variables: ob_outputDirectory: '$(REPOROOT)\out' ob_sdl_binskim_break: true steps: - task: Bash@3 displayName: "Run tests" inputs: targetType: 'inline' workingDirectory: $(FRAMEWORK_DIR) script: | make test - task: Bash@3 displayName: "Run unit tests report" inputs: filePath: $(Build.SourcesDirectory)/src/framework/scripts/run-unit-tests-report
解决方案
核心思路是把原来分属两个Stage的所有步骤合并到同一个Job中——因为同一个Job会在同一个容器实例中运行,天然满足顺序执行和同容器的要求。
修改后的YAML示例:
- stage: build_and_test jobs: - job: build_and_test_main pool: type: linux variables: ob_outputDirectory: '$(REPOROOT)\out' ob_sdl_binskim_break: true steps: # 原build阶段的环境搭建步骤 - task: Bash@3 displayName: "Install conda/python3.10, unixodbc, pytest and requirements" inputs: targetType: 'inline' workingDirectory: $(FRAMEWORK_DIR) script: | make setup-python-in-ubuntu make setup-local # 原test阶段的测试步骤,按顺序执行 - task: Bash@3 displayName: "Run tests" inputs: targetType: 'inline' workingDirectory: $(FRAMEWORK_DIR) script: | make test - task: Bash@3 displayName: "Run unit tests report" inputs: filePath: $(Build.SourcesDirectory)/src/framework/scripts/run-unit-tests-report
补充说明
- 若需要保留Stage的逻辑(比如后续可能扩展并行Stage),也可以只保留一个Stage,在其中放置一个Job,把所有步骤按顺序放入该Job即可
- 同一个Job内的步骤默认顺序执行,前一个步骤失败后,后续步骤会自动终止(可通过
continueOnError参数调整) - 变量只需在Job级别统一定义,无需重复声明
内容的提问来源于stack exchange,提问作者WestCoastProjects
相关产品推荐
相关产品推荐

