Circle CI 2.0でステップが失敗しても次のステップを実行したい

Posted on
Circle CI

ステップが失敗しても次のステップを実行したい

Circle CI 1.0とは異なり、2.0ではステップが失敗すると次のステップは実行されません
ちなみにコマンドの戻り値が0以外であれば失敗となります。

例: 2つめのステップは実行されません。

version: 2
jobs:
  build:
    docker:
      - image: circleci/ruby:2.5.0
    steps:
      - run:
          command: |
            echo "This is first step"
            exit 1            
      - run:
          command: echo "This is second step"

結果:

$ circleci build

====>> Spin up Environment
Build-agent version 0.0.4984-b7b3a27 (2018-04-23T16:25:42+0000)
Starting container circleci/ruby:2.5.0
...
====>> echo "This is first step"
exit 1

  #!/bin/bash -eo pipefail
echo "This is first step"
exit 1

This is first step
Error: Exited with code 1
Step failed
Task failed

しかし、たとえばあるステップでテストが失敗しても、その後のステップでLintを必ず走らせたいようなニーズはけっこうあると思います。
そんなときはwhen: alwaysを使うと良いです。

例: 2つめのステップも実行されます

version: 2
jobs:
  build:
    docker:
      - image: circleci/ruby:2.5.0
    steps:
      - run:
          command: |
            echo "This is first step"
            exit 1            
      - run:
          command: echo "This is second step"
          when: always

結果:

$ circleci build

====>> Spin up Environment
Build-agent version 0.0.4984-b7b3a27 (2018-04-23T16:25:42+0000)
Starting container circleci/ruby:2.5.0
...
====>> echo "This is first step"
exit 1

  #!/bin/bash -eo pipefail
echo "This is first step"
exit 1

This is first step
Error: Exited with code 1
Step failed
====>> echo "This is second step"
  #!/bin/bash -eo pipefail
echo "This is second step"
This is second step
Task failed

これで2つめのステップも実行されるようになりました。
ただし、 全体の実行結果は「失敗」 となります。ステップが1つでも失敗したら全体の結果は失敗となったほうが良いのでこの挙動が問題になることはあまりないのかなと思います。

ステップが失敗した後にだけ任意のステップを実行したい

when: on_failを使います。
例えば、失敗したときに通知を飛ばしたい、失敗したときだけ特定のファイルを保存したいなどといったときに便利です。

例:

version: 2
jobs:
  build:
    docker:
      - image: circleci/ruby:2.5.0
    steps:
      - run:
          name: Step 1
          command: |
            echo "This is Step 1"
            exit 1            
      - run:
          name: Step 2
          command: echo "This is Step 2"
      - run:
          name: Step 3
          command: echo "This is Step 3"
          when: on_fail

結果:

$ circleci build
====>> Spin up Environment
Build-agent version 0.0.4984-b7b3a27 (2018-04-23T16:25:42+0000)
...
====>> Step 1
  #!/bin/bash -eo pipefail
echo "This is Step 1"
exit 1

This is Step 1
Error: Exited with code 1
Step failed
====>> Step 3
  #!/bin/bash -eo pipefail
echo "This is Step 3"
This is Step 3
Task failed

whenのデフォルト値はon_successなのでStep 2は実行されず、Step 3が実行されます。