在 CircleCI 中并行执行多个步骤

问题描述 投票:0回答:1

我有一个具有以下结构的 CircleCI 作业。

jobs:
  test:
    steps:
      - checkout
      - run #1
        ...<<install dependencies>>
      - run #2
        ...<<execute server-side test>>
      - run #3
        ...<<execute frontend test 1>> 
      - run #4
        ...<<execute frontend test 2>> 

我想先执行步骤#1,然后并行执行步骤#2-4。
#1、#2、#3 和 #4 分别需要约 4 分钟、约 1 分钟、约 1 分钟和约 1 分钟。

我尝试将步骤拆分为不同的作业,并使用 workspaces 将已安装的工件从 #1 传递到 #2-4。然而,由于文物尺寸较大,大约需要 2 分钟。保留并附加工作区,因此分割作业的优势被抵消了。

有没有一种聪明的方法可以并行运行#2-4,而不会产生大量开销?

circleci
1个回答
2
投票

如果您想并行运行命令,则需要将这些命令移至新作业中,否则,CircleCI 将遵循您的步骤结构,仅在最后一个命令完成后才运行命令。让我举一个例子。我创建了一个包含 4 个作业的基本配置。

    • npm install
    • test1
      (将与以下同时运行) test2) 但仅当
      npm install
      完成
    • test2
      (这将 与 test1 同时运行,但仅当
      npm install
      完成
    • deploy
      (只有在完成 2 个测试后才会运行)

基本上,您需要在作业之间拆分命令并根据需要设置依赖关系。

查看我的配置文件:

jobs:
  install_deps:
    docker:
      - image: circleci/node:14

    steps:
      - checkout
      - setup_remote_docker:
          docker_layer_caching: true
      
      - run: echo "running npm install"
      - run: npm install
      - persist_to_workspace:
          root: .
          paths:
            - '*'
  test1:
    docker:
      - image: circleci/node:14

    steps:
      - checkout
      - setup_remote_docker:
          docker_layer_caching: true
      - attach_workspace:
            at: .

      - run: echo "running the first test and also will run the test2 in parallel"
      - run: npm test

  test2:
    docker:
      - image: circleci/node:14

    steps:
      - checkout
      - setup_remote_docker:
          docker_layer_caching: true
      - attach_workspace:
            at: .

      - run: echo "running the second test in parallel with the first test1"
      - run: npm test
  deploy:
    docker:
      - image: circleci/node:14

    steps:
      - checkout
      - setup_remote_docker:
          docker_layer_caching: true
      - attach_workspace:
            at: .

      - run: echo "running the deploy job only when the test1 and test2 are finished"
      - run: npm run build

# Orchestrate our job run sequence
workflows:
  test_and_deploy:
    jobs:
      - install_deps
      - test1:
          requires:
              - install_deps
      - test2:
          requires:
              - install_deps
      - deploy:
          requires:
              - test1
              - test2

现在看上面的逻辑,

install_dep
将在没有依赖的情况下运行,但是
test1
test2
将在
install_dep
完成之前不会运行。

此外,在两个测试完成之前,

deploy
不会运行。

我已经运行了这个配置,在第一张图片中我们可以看到其他作业正在等待第一个作业完成,在第二张图片中我们可以看到两个测试正在并行运行,并且

deploy
作业正在等待他们完成。在第三张图片中,我们可以看到
deploy
作业正在运行。

© www.soinside.com 2019 - 2024. All rights reserved.