如何在Google Cloud Function中获取Google Cloud构建列表?
解答
该需求可实现,无需在Cloud Function中执行gcloud命令,直接调用Google官方Cloud Build Node.js SDK即可拿到和gcloud builds list --ongoing完全一致的结果。
前置配置
- 为Cloud Function绑定的运行时服务账号授予Cloud Build资源的列表查询权限,最小权限可绑定
Cloud Build Viewer角色。 - 若你需要查询指定区域的构建记录,初始化SDK时配置对应区域的API端点即可,默认配置会查询项目全局的构建记录。
代码实现
- 先在Function的
package.json中添加官方SDK依赖:
{ "dependencies": { "@google-cloud/cloudbuild": "^3.2.0" } }
- 在
index.js中编写逻辑,过滤状态为运行中的构建,和原bash命令逻辑对齐:
const { CloudBuildClient } = require('@google-cloud/cloudbuild'); // 初始化客户端,若需指定区域可传入参数:new CloudBuildClient({ apiEndpoint: '对应区域-cloudbuild.googleapis.com' }) const cbClient = new CloudBuildClient(); exports.processPubSubMessage = async (event, context) => { // 拉取正在运行的构建:status=WORKING 即对应--ongoing参数的过滤条件 const [builds] = await cbClient.listBuilds({ projectId: process.env.GCP_PROJECT, filter: 'status="WORKING"' }); // 业务逻辑:匹配目标触发器的运行中构建 const TARGET_TRIGGER_ID = "替换为你要关联的Cloud Build触发器ID"; const targetBuildRunning = builds.some(build => build.buildTriggerId === TARGET_TRIGGER_ID); if (targetBuildRunning) { console.log("目标触发器存在运行中的构建,跳过消息发布"); return; } // 此处编写无运行中构建时的消息发布逻辑 console.log("校验通过,执行消息发布"); };
补充说明
- gcloud CLI本身就是对Cloud Build API的封装,SDK调用和gcloud命令底层走的是同一套接口,返回结果无差异,稳定性远高于在Function中安装gcloud执行shell命令的方案(后者冷启动慢、依赖问题多,不推荐)。
- 返回的构建对象包含构建ID、触发器ID、状态、开始时间等全量字段,可直接根据你的业务规则做过滤判断,不需要额外调用其他接口。
内容的提问来源于stack exchange,提问作者FDM
相关产品推荐
相关产品推荐

