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

如何配置Cloud Build推送时运行Cloud Source Repo内的gcloud shell脚本及示例

实现方案及示例

完全可以实现你要的推送触发执行效果,不需要依赖Python/Node.js运行时,直接用Cloud Build官方提供的gcloud镜像运行shell脚本即可,具体配置参考如下:

前置配置

  • 给Cloud Build默认服务账号授予对应权限:至少分配Compute Admin、Service Account User两个角色,避免创建VM时权限不足
  • 在Cloud Build控制台创建触发器,绑定你的Cloud Source Repo仓库,触发规则设置为指定分支(如main)推送代码时触发

仓库文件结构示例

仓库根目录
├── cloudbuild.yaml
└── scripts
    └── create_vm.sh

shell脚本示例(create_vm.sh)

提交代码到仓库前先本地执行chmod +x scripts/create_vm.sh给脚本加可执行权限:

#!/bin/bash
# 示例:创建e2-micro规格VM,可自行替换参数、扩展其他gcloud操作
gcloud compute instances create demo-vm \
  --zone=us-central1-a \
  --machine-type=e2-micro \
  --image-family=debian-12 \
  --image-project=debian-cloud \
  --boot-disk-size=10GB

cloudbuild.yaml配置示例

steps:
  # 步骤1:补全脚本执行权限,避免提交时权限丢失导致运行失败
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - 'chmod +x ./scripts/create_vm.sh'
  # 步骤2:执行创建VM的shell脚本
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - './scripts/create_vm.sh'
# 可选:配置日志输出到Cloud Logging,无需额外存储桶
options:
  logging: CLOUD_LOGGING_ONLY

验证方式

配置完成后向绑定分支推送一次代码,到Cloud Build控制台即可看到对应执行任务,点击任务可查看每一步的执行日志,运行失败也能直接定位报错原因。

注意:脚本中不要硬编码敏感信息,相关密钥建议存放在Secret Manager中,Cloud Build支持直接调用Secret Manager的密文内容,避免信息泄露。

内容的提问来源于stack exchange,提问作者Indrid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:36:04