cilphex
cilphex

Reputation: 6096

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

I have automatic builds set up in Google Cloud, so that each time I push to the master branch of my repository, a new image is built and pushed to Google Container Registry.

These images pile up quickly, and I don't need all the old ones. So I would like to add a build step that runs a bash script which calls gcloud container images list-tags, loops the results, and deletes the old ones with gcloud container images delete.

I have the script written and it works locally. I am having trouble figuring out how to run it as a step in Cloud Builder.

It seems there are 2 options:

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

In the above step in cloudbuild.yml I try to run the bash command in the ubuntu image. This doesn't work because the gcloud command does not exist in this image.

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

In the above step in cloudbuild.yml I try to use the gcloud image, but since "Arguments passed to this builder will be passed to gcloud directly", I don't know how to call my bash script here.

What can I do?

Upvotes: 2

Views: 8598

Answers (2)

gso_gabriel
gso_gabriel

Reputation: 4660

As per the official documentation Creating custom build steps indicates, you need a custom build step to execute a shell script from your source, the step's container image must contain a tool capable of running the script.

The below example, shows how to configure your args, for the execution to perform correctly.

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']

I would recommend you to take a look at the above documentation and the example as well, to test and confirm if it will help you achieve the execution of the script.

For your case, specifically, there is this other answer here, where is indicated that you will need to override the endpoint of the build to bash, so the script runs. It's indicated as follow:

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

Besides that, these two below articles, include more information and examples on how to configure customized scripts to run in your Cloud Build, that I would recommend you to take a look.

Let me know if the information helped you!

Upvotes: -1

guillaume blaquiere
guillaume blaquiere

Reputation: 75705

You can customize the entry point of your build step. If you need gcloud installed, use the gcloud cloud builder and do this

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

Upvotes: 10

Related Questions