How to Retry a Failed Step with "when" Attribute?

Sometimes it becomes very important to retry a failed step instead of re-running a complete job (obviously to save time and money). In this article, we will see how to retry a step when it is failed using the "when" attribute with the help of a simple example. 

 First of all, let see what are the different parameters of when attribute.

  1. when: on_success >  This is the default option and means that the step will run only if all of the previous steps have been successful (returned exit code 0).
  2. when: always > This means that the step will run regardless of the exit status of previous steps.
  3. when: on_fail > This means that the step will run only if one of the preceding steps has failed (returns a non-zero exit code)

 

Retrying a Failed Step

By default, CircleCI will execute job steps one at a time, in the order that they are defined in config.yml, until a step fails (returns a non-zero exit code). After a command fails, no further job steps will be executed.

Adding the when attribute to a job step allows you to override this default behaviour, and selectively run or skip steps depending on the status of the job.

 Now, let's understand this through a working example that how you can use when: on_fail to retry a failed step. 

 Below is the sample config.yml file where the step "Run on fail status" will trigger as the output of the previous step is a failure (exit 1).

 

version: 2.1

workflows:
  version: 2
  build_deploy:
    jobs:
      - build

jobs:
  build:

    docker:
      - image: circleci/python:3.7.5
    steps:
      - checkout
      - run:
          name: Run commands
          command: |
              echo "I will exit fail status"
              exit 1
      - run:
          name: Run on fail status
          command: |
              echo "I am result of above failed job"
          when: on_fail

 

The below screenshot shows the triggering of step containing "when" attribute when previous step fails. 

when attribute CircleCI - fail

Note: The state of the workflow, in this case, will be FAILED.

 

 Below is the sample config.yml file where the step "Run on fail status" will not trigger as the output of the previous step is a success (exit 0).

version: 2.1

workflows:
  version: 2
  build_deploy:
    jobs:
      - build

jobs:
  build:

    docker:
      - image: circleci/python:3.7.5
    steps:
      - checkout
      - run:
          name: Run commands
          command: |
              echo "I will exit success status"
              exit 0
      - run:
          name: Run on fail status
          command: |
              echo "I am result of above failed job"
          when: on_fail

  

when attribute CircleCI - Success

 

This was a simple demonstration of how you can use when attribute to retry a failed step.

Happy Building!

Was this article helpful?
0 out of 1 found this helpful

Comments

0 comments

Article is closed for comments.