How to ignore "image not found" error in cloudbuild.yaml when deleting images from the artifact registry?

826 Views Asked by At

Currently the cloudbuild.yaml looks like this:

steps:
- name: 'gcr.io/cloud-builders/gcloud'
  args: [ 'artifacts', 'docker', 'images', 'delete', 'location-docker.pkg.dev/$PROJECT_ID/repository/image' ]
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-t', 'location-docker.pkg.dev/$PROJECT_ID/repository/image:latest', './' ]
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'location-docker.pkg.dev/$PROJECT_ID/reporitory/image:latest']
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
  entrypoint: gcloud
  args: ['run', 'deploy', 'image', '--image', 'us-east1-docker.pkg.dev/$PROJECT_ID/cb-area52-ar/area52-image:latest', '--region', 'region']


images:
- 'location-docker.pkg.dev/$PROJECT_ID/registry/image:latest'

That does basically the following:

  1. delete the existsing image in the artifact registry
  2. build the new image
  3. pushes it back to the artifact registry
  4. deploys it to google cloud run

My problem is now that the first step fails whenever there is no image in the registry.

How can i prevent it from cancelling the whole build process when this occurs?

1

There are 1 best solutions below

1
On BEST ANSWER

You can create an inline script to check whether the image exists or not. This assumes you always want to delete the image with the latest tag.

steps:
- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-eEuo'
  - 'pipefail'
  - '-c'
  - |-
    if [[ -z `gcloud artifacts docker images describe location-docker.pkg.dev/$PROJECT_ID/repository/image:latest --verbosity=none --format=text` ]]
    then
      echo "Image does not exist. Continue with the build"
    else
      echo "Deleting Image"
      gcloud artifacts docker images delete location-docker.pkg.dev/$PROJECT_ID/repository/image
    fi