Search code examples
amazon-web-servicesaws-cliaws-codepipelineaws-codebuildaws-step-functions

Check for step function status in code build and control the pipeline behaviour


I have a code build pipeline which executes a step function in the commands section. Below is the snippet of the code build pipeline

version: "0.2"
env:
  git-credential-helper: "yes"
  shell: bash
  variables:
    PROFILEFLAGS: ""
phases:
  install:
    commands:
      - npm install jsonlint -g
  pre_build:
    commands:
      - echo "pre_build"

  build:
    on-failure: ABORT
    commands:
      - aws stepfunctions start-execution --state-machine-arn arn:aws:states:${AWS_REGION}:${TARGET_ACCOUNT}:stateMachine:${STEP_FUNCTION} --name Ab-sf-$CODEBUILD_BUILD_NUMBER --input "xyz.json"

  post_build:
    commands:
      - echo "Display Last Changes"
artifacts:
  files:
    - xyz.json

The current issue with this is, the build proceeds while the step function is being executed. I would like to have a condition which does below:

  1. If step function is in running state, then wait until it finishes.
  2. If step function is in succeeded state then proceed to the next command.

What would be the recommended way to address this.


Solution

  • This is rather easy to implement by creating a script with a monitoring loop which updates the state machine status by using AWS CLI command aws stepfunctions describe-execution

    Below is an example code. Feel free to add more sophisticated error and exception handling and execution logic.

    #!/bin/bash
    
    main() {
     
      start_execution # Start state machine execution
      
      monitor_execution # Start monitoring loop
      
      echo "{\"status\":\"$EXECUTION_STATUS\"}" # Print script output as JSON string.
    
      if [ $EXECUTION_STATUS != "SUCCEEDED" ] 
        then 
          exit 1 # Set exit code to 1 (error) if buid was not successful
        else 
          exit 0 # Set exits code to 0 (success) if build was successful
        fi
    
    }
    
    # Starts Step Functions state machine
    start_execution() {
      EXECUTION_ARN=$(aws stepfunctions start-execution --state-machine-arn [arn] --input {} --region [region] | jq -r '.executionArn | tostring')
      EXECUTION_STATUS="RUNNING" # Initialize executions status for the first iteration of monitoring loop. 
    }
    
    # Monitors execution status. When status changes from RUNNING to some other state, function calls error handling function
    monitor_execution () {
      until [ $EXECUTION_STATUS != "RUNNING" ]
      do
        sleep [value] # Monitoring loop sleep time
        update_execution_status # Update status for the next comparison
      done
    }
    
    update_execution_status() {
      EXECUTION_STATUS=$(aws stepfunctions describe-execution --execution-arn ${EXECUTION_ARN} --region [region] | jq -r .status)
    }
    
    
    if [ "$0" == "${BASH_SOURCE[0]}" ] ; then
      main "$@"
    fi