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

时间:2020-03-24 05:57:01

标签: google-cloud-platform google-cloud-build

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

这些图像迅速堆积,我不需要所有旧图像。因此,我想添加一个运行bash脚本的构建步骤,该脚本调用gcloud container images list-tags,循环结果,并使用gcloud container images delete删除旧的脚本。

我已经编写了脚本,并且可以在本地工作。我无法确定如何在Cloud Builder中运行它。

似乎有2种选择:

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

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

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

cloudbuild.yml的上述步骤中,我尝试使用gcloud图像,但是由于“传递给此构建器的参数将直接传递给gcloud”,因此我不知道如何在这里调用我的bash脚本。

我该怎么办?

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:-1)

根据官方文档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']

我建议您同时阅读上述文档和示例,以测试并确认是否可以帮助您完成脚本的执行。

对于您的情况,具体地说,还有另一个答案here,表明您需要将构建的端点覆盖到bash,脚本才能运行。指示如下:

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

此外,以下这两篇文章还提供了有关如何配置自定义脚本以在Cloud Build中运行的更多信息和示例,我建议您看看。

让我知道信息是否对您有帮助!