Running a Different Job if the Previous Succeeds or Fails

I’m trying to create a config file that follows the following pattern:

  1. Run a command (terraform) that will either return an exit code 0 (everything is fine) or 2 (changes are needed)
  2. If everything is fine (0 code) then the workflow is done and it can move on
  3. If the command says that things need changing (2 code), I want circleci to run a manual approval state so that I can check things over before it proceeds.

Is this possible?

I tried to do this with steps, but it appears that manual approval is only allowed for jobs. I found the very helpful step when with condition: on_fail but I don’t know if or how it could trigger a different job to run or be skipped.

My first attempt went something like this:

- run:
      name: Plan Terraform
      command: |
        cd ./bin
        planresult=$(terraform plan)
        if [[ $? != 0 ]]; then
          exit 2
        else
          exit 0
        fi
  - when:
      condition: on_fail
      steps:
         ????

You are looking for a workflow that goes:

Job 1  ----> Pass -> Deploy
       L---> Fail   -> Approval -> Deploy

If I am understanding things correctly?

2 Likes

Yes, that’s correct. Is this possible at the moment with CircleCI?

You should be able to do the approval job as a condition: on_fail and make the deploy job require that. I think you may want to duplicate the deploy job though, one for success, and one for after the approval job.

You can make the two jobs less messy but using anchors https://circleci.com/docs/2.0/writing-yaml/#anchors-and-aliases for the steps.

Thanks for the tip. Do you mean that using the when step you can trigger the approval job?

   plan_job -->  (when, condition: on_fail) -->  approval_job --> deploy_job
                   L(when, condition: on_success) --> deploy_job

I can’t find any reference on how to point the when/condition to a job though, and the docs are limited in examples. I’ve only found this for the when step: https://circleci.com/docs/2.0/configuration-reference/#the-when-step-requires-version-21

So, based on what you say, I could use an anchor for the two options (success and failure) so that I don’t have to duplicate things. That sounds fine, but I’m not sure how to get the approval step in there as that drops back out to the job level, and I don’t see any condition option in the workflow/job https://circleci.com/docs/2.0/configuration-reference/#jobs-1.

Ugg, no, I wasn’t thinking this through fully. Maybe an empty job that just echos something has the when, and the approval job requires that?

We might just be stuck asking you to vote for this feature request https://ideas.circleci.com/ideas/CCI-I-605 (which I forgot existed)

Have you found a way to do this: branching a workflow based on the status of a job yet?

1 Like