如何在构建步骤中从 shell 脚本调用 gcloud 命令?

How can I call gcloud commands from a shell script during a build step?

我在 Google 云中设置了自动构建,因此每次我推送到存储库的 master 分支时,都会构建一个新映像并将其推送到 Google Container Registry。

这些图像堆积得很快,我不需要所有旧的。所以我想添加一个构建步骤,运行 是一个调用 gcloud container images list-tags 的 bash 脚本,循环结果,并使用 gcloud container images delete.[=22= 删除旧的]

我已经编写了脚本并且可以在本地运行。我无法弄清楚如何 运行 它作为 Cloud Builder 中的一个步骤。

好像有两个选项:

- name: 'ubuntu'
  args: ['bash', './container-registry-cleanup.sh']

cloudbuild.yml 的上述步骤中,我尝试 运行 ubuntu 图像中的 bash 命令。这不起作用,因为此图像中不存在 gcloud 命令。

- name: 'gcr.io/cloud-builders/gcloud'
  args: [what goes here???]

cloudbuild.yml 的上述步骤中,我尝试使用 gcloud 图像,但是由于 "Arguments passed to this builder will be passed to gcloud directly",我不知道如何调用我的 bash 脚本这里。

我能做什么?

根据官方文档 Creating custom build steps 指出,您需要一个自定义构建步骤来从源代码执行 shell 脚本,该步骤的容器映像必须包含一个能够 运行宁脚本。

以下示例展示了如何配置您的 args,以便正确执行。

steps:
- name: 'ubuntu'
  args: ['bash', './myscript.bash']
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t', 'gcr.io/$PROJECT_ID/custom-script-test', '.']
images: ['gcr.io/$PROJECT_ID/custom-script-test']

我建议你也看看上面的文档和示例,测试并确认它是否能帮助你实现脚本的执行。

对于您的情况,具体而言,还有另一个答案 ,其中表明您需要将构建的端点覆盖为 bash,因此脚本 运行s。表示如下:

- name: gcr.io/cloud-builders/gcloud
  entrypoint: /bin/bash
  args: ['-c', 'gcloud compute instances list > gce-list.txt']

除此之外,下面这两篇文章包含更多关于如何在 Cloud Build 中为 运行 配置自定义脚本的信息和示例,我建议您看一看。

如果这些信息对您有帮助,请告诉我!

您可以自定义构建步骤的入口点。如果您需要安装 gcloud,请使用 gcloud cloud builder 并执行此操作

step:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: "bash"
    args:
      - "-c"
      - |
          echo "enter 1 bash command per line"
          ls -la
          gcloud version
          ...