Example bash script to get details about why a step failed

Hi There!

Recently the Support team created a script to easily get the last few lines of a failed step. This script can be used to pull details via the API on why a step exited as it returns the last 20 lines of the log output.

This script will likely need to be modified to be used for your purposes, but should be a good starting point!

A few notes/caveats:

  1. It only pulls the last 20 lines of the step, modify the 20 in the tail -n 20 line if you need to adjust
  2. It requires jq to be installed
  3. Within the Variables section, you will need to enter your API token, organization and project
#!/bin/bash -e

# Can be called with "sh name_of_file.sh" -- you will be prompted for a Job number

### Variables ###
​
# Set to your personal API token
CIRCLE_API_TOKEN=""
# Set to your organization
ORG=""
# Set to your project
PROJECT=""
# Set to your VCS (github or bitbucket)
VCS="github"
​
### Commands ###

# Check for Input
read -p 'Job Number: ' JOB
​
if [ -z "$JOB" ]
  then
    echo "No argument supplied, please enter a Job Number."
    exit 1
fi

FAILED_STEP=$(curl "https://circleci.com/api/v1.1/project/$VCS/$ORG/$PROJECT/$JOB?circle-token=$CIRCLE_API_TOKEN" | jq '.steps | .[] | flatten | map(select(.status? == "failed")) | .[] | {allocation_id, step}')

ALLOCATION_ID=$(echo "${FAILED_STEP}" | jq -r '.allocation_id')
STEP=$(echo "${FAILED_STEP}" | jq -r '.step')

curl "https://circleci.com/api/v1.1/project/$VCS/$ORG/$PROJECT/$JOB/output/$STEP/0?file=true&allocation-id=$ALLOCATION_ID&circle-token=$CIRCLE_API_TOKEN" | tail -n 20
​
#### END ####
5 Likes