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

基于GCP Cloud Build的云函数CI流水线条件部署问题

解决GCP Cloud Build中Behave测试失败仍部署云函数的问题

问题背景

为GCP云函数搭建基于Cloud Build的CI流水线,使用Behave做Python测试,期望流程:

  • 借助functions-framework运行Behave测试
  • 将测试结果上传至存储桶
  • 仅当测试成功时部署函数到测试环境

当前问题:无论Behave测试是否成功,函数都会被部署,原因是测试结果通过管道输出时,后续写入操作的成功掩盖了测试的退出状态。需求是步骤1、2始终执行,测试失败则跳过步骤3并标记构建失败。

解决方案

核心思路:捕获Behave测试的真实退出码并持久化,基于该退出码控制部署步骤的执行,同时确保测试失败时整个构建标记为失败。

1. 修改cloudbuild.yaml

调整步骤逻辑,添加退出码捕获、条件部署及构建失败标记:

steps:
  - id: 'run-behave-tests'
    name: 'gcr.io/my-project/my-docker-image:v1'
    entrypoint: /bin/bash
    args: 
      - -c 
      - |
          pip install -r ./gcfs/hello/requirements.txt && 
          cd ./gcfs/hello && 
          # 启动functions-framework后台运行
          (functions-framework --target=hello --signature-type=http --port=8080) & 
          sleep 10 && 
          cd ./gcfs/hello && 
          # 运行Behave测试并捕获退出码
          behave --tags=local --format json --no-skipped --no-source --no-summary | 
          jq '.[] |= {"function_name": "hello"} + .' | 
          jq -c ".[]" > /workspace/behave_output_hello.json;
          # 保存Behave的退出码到文件(PIPESTATUS[0]是behave命令的退出码)
          TEST_EXIT_CODE=${PIPESTATUS[0]}
          echo $TEST_EXIT_CODE > /workspace/test_exit_code.txt
    # 允许此步骤失败,确保后续上传结果步骤能执行
    allowFailure: true

  - id: 'upload-behave-results'
    name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    args:
      - gcloud
      - storage
      - cp
      - --content-type=text/plain
      - /workspace/behave_output_hello.json
      - gs://bucketbucketbucket/behave_output.json

  - id: 'check-test-status'
    name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: /bin/bash
    args:
      - -c
      - |
          EXIT_CODE=$(cat /workspace/test_exit_code.txt)
          if [ $EXIT_CODE -ne 0 ]; then
            echo "Behave测试失败,退出码: $EXIT_CODE"
            exit 1
          fi

  - id: 'deploy-function'
    name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    # 仅当测试成功(退出码为0)时执行此步骤
    if: '$(cat /workspace/test_exit_code.txt) == "0"'
    args:
      - gcloud
      - functions
      - deploy
      - function-name
      - --region=us-central1
      - --source=https://MYCLOUDREPO/revisions/dev/paths/gcfs/hello
      - --trigger-http
      - --runtime=python311
      - --project=myproject

options:
  logging: CLOUD_LOGGING_ONLY

关键调整说明

  • 捕获退出码:使用${PIPESTATUS[0]}获取Behave命令的真实退出码(管道中第一个命令的退出状态),并写入/workspace/test_exit_code.txt(Cloud Build步骤间通过/workspace共享文件)。
  • 允许测试步骤失败:给run-behave-tests步骤添加allowFailure: true,确保即使测试失败,后续上传结果的步骤仍能执行。
  • 条件部署:deploy-function步骤通过if字段判断退出码是否为0,仅满足条件时执行部署。
  • 标记构建失败:新增check-test-status步骤,读取退出码,若不为0则主动退出并标记构建失败。

2. Docker镜像无需修改

当前的my-docker-image已包含所需依赖(behave、requests、jq),无需调整。

内容的提问来源于stack exchange,提问作者Jeffrey Van Laethem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:35:11