Conditioning a step on the EXIT_CODE of the previous step

I want to achieve the following:

steps:
  - label: "failing step"
    command: exit -1

  - wait

  - label: "run ONLY if previous step has non-zero exit status"
    command: echo "PREV STEP FAILED"
    if: (prev_step_exit_code != 0) # how do i change this here?

The idea is to conditionally run a step based on the exit status of the previous step, but i’m not exactly sure if this is the right way to do it. Is this possible?

I could be wrong here, but I think this is not possible at this moment, as all the steps are load when we run the upload command and all the conditions are evaluated at that time. The workaround is to upload a value into metadata and read it in the next step, which could exit early conditionally.

Hmm thanks for your feedback on this. I looked around and saw that theres a buildkite environment variable BUILDKITE_COMMAND_EXIT_STATUS, which basically stores the exit code from the last command run in the command hook.

However, right now its not showing up on the environment tab of my build step. Any idea?

​Hi Jaganiku and welcome!

@xiaket is correct because the value is not known when the build is created.

The way you could achieve this would be to use the buildkite-agent steps get command to grab the step outcome and do a dynamic upload to create the next step(s); you could do it in the step or in a script. Here is one that I created in the Buildkite YAML editor for an example:

steps:
  - label: 'Step 1'
    command: "true"
    key: 'one'
  
  - wait:
    continue_on_failure: true
    
  - label: 'Step 2'
    command: |
      if [ $$(buildkite-agent step get "outcome" --step "one") == "passed" ]; then
        buildkite-agent pipeline upload .buildkite/my-steps.yml
      fi
1 Like

Hi Jason,

Thanks for your input on this, I decided to script it in the end. Really appreciate the time and effort you put into answering this newbie’s post. Great community! (: