使用 needs 语法控制任务依赖

本文主要介绍如何使用 needs 语法控制 Job 执行顺序。

  • 云效流水线 YAML 支持 stages.<stage_id>.jobs.<job_id>.needs 语法定义 Job 依赖。

  • 典型场景如下:app1、app2 需要一起构建部署:app1构建任务依赖app1单元测试和app1代码扫描任务都完成,app2构建任务依赖app2单元测试和app2代码扫描任务都完成,app1和app2构建阶段可以并行,用于提升效率;app2部署依赖app1部署完成。

  • 上述场景示例 YAML 和运行效果如下:

    image

    sources: 
      my_repo1:
        type: gitSample
        name: app1代码源
        endpoint: https://atomgit.com/flow-example/spring-boot.git
        branch: master
      my_repo2:
        type: gitSample
        name: app2代码源
        endpoint: https://atomgit.com/flow-example/node-expressjs.git
        branch: master
    defaultWorkspace: my_repo1
    stages:
      build_stage:
        name: 构建
        jobs:
          test_job1:
            name: app1单元测试
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
          scan_job1:
            name: app1代码扫描
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
          test_job2:
            name: app2单元测试
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
          scan_job2:
            name: app2代码扫描
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
          build_job1:
            name: app1构建
            # 声明依赖任务,app1构建依赖app1单元测试和代码扫描任务都完成
            needs: 
              - test_job1
              - scan_job1
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
          build_job2:
            name: app2构建
            # 声明依赖任务,app2构建依赖app2单元测试和代码扫描任务都完成
            needs: 
              - test_job2
              - scan_job2
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: |
                    echo This is build job...
      deploy_stage:
        name: 部署
        jobs:
          deploy_job1:
            name: app1部署
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: echo This is deploy env 1...
          deploy_job2:
            name: app2部署
            # 声明依赖任务,app2部署依赖app1部署任务完成
            needs: deploy_job1
            steps:
              command_step:
                name: 执行命令
                step: Command
                with:
                  run: echo This is deploy env 2...