You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CodeBuild中检查Step Function状态并控制流水线行为

解决CodeBuild流水线中等候Step Function执行完成的方案

现有CodeBuild流水线在build阶段启动Step Function后,流程会直接推进至post_build阶段,无法等待Step Function执行完成。需要实现两个核心逻辑:等待Step Function执行结束,且仅在执行成功时才继续后续步骤。

推荐解决方案

核心思路是:启动Step Function后捕获执行ARN,通过轮询查询执行状态,直至进入终端状态;仅当状态为SUCCEEDED时才继续流水线,否则终止并抛出错误。

修改后的完整流水线配置

version: "0.2"
env:
  git-credential-helper: "yes"
  shell: bash
  variables:
    PROFILEFLAGS: ""
phases:
  install:
    commands:
      - npm install jsonlint -g
      - # 安装jq用于解析AWS CLI的JSON输出(若CodeBuild环境默认无jq则需添加)
      - apt-get update && apt-get install -y jq
  pre_build:
    commands:
      - echo "pre_build"

  build:
    on-failure: ABORT
    commands:
      - # 启动Step Function并捕获执行ARN
      - EXECUTION_ARN=$(aws stepfunctions start-execution --state-machine-arn arn:aws:states:${AWS_REGION}:${TARGET_ACCOUNT}:stateMachine:${STEP_FUNCTION} --name Ab-sf-$CODEBUILD_BUILD_NUMBER --input file://xyz.json --query 'executionArn' --output text)
      - echo "Started Step Function execution: $EXECUTION_ARN"
      
      - # 轮询查询执行状态,直至退出RUNNING状态
      - while true; do
          EXECUTION_STATUS=$(aws stepfunctions describe-execution --execution-arn $EXECUTION_ARN --query 'status' --output text)
          if [ "$EXECUTION_STATUS" != "RUNNING" ]; then
            break
          fi
          echo "Step Function execution is still running, waiting 30 seconds..."
          sleep 30
        done
      
      - # 判断执行状态,非成功则终止流水线
      - if [ "$EXECUTION_STATUS" != "SUCCEEDED" ]; then
          echo "Step Function execution failed with status: $EXECUTION_STATUS"
          exit 1
        fi
      - echo "Step Function execution completed successfully"

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

关键说明

  • jq安装:部分CodeBuild标准镜像默认未预装jq,需在install阶段添加安装命令;若使用的镜像已包含jq,可跳过此步骤。
  • 输入文件处理:--input file://xyz.json会将本地xyz.json文件的内容作为输入传递给Step Function,若原逻辑是传递字符串"xyz.json",可改回--input "\"xyz.json\""。
  • 轮询间隔:示例中使用30秒间隔,可根据Step Function的预期执行时长调整(如10秒)。
  • 权限配置:确保CodeBuild使用的服务角色拥有states:StartExecution和states:DescribeExecution的IAM权限。
  • 错误处理:当Step Function进入FAILED/TIMED_OUT/ABORTED等终端状态时,流水线会直接终止并返回错误,符合on-failure: ABORT的配置。

内容的提问来源于stack exchange,提问作者B.T Anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:50:38