The simplest and most generic Google Cloud Build yaml config file ever

Hiring

We are Binx. We make every organization cloud-native.

While doing Cloud Native migrations, we depend on container images a lot. In this mini-blog I will present you with the
simplest Google Cloud Build config file that will build both snapshot and release versions at the same time.

Google Cloud Build configuration

Without further ado: here is the simplest and most generic Google Cloud Build YAML config file for building container images:

steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', '${_IMAGE}', '.']

images: ['${_IMAGE}']

substitutions:
  _IMAGE: 'gcr.io/${PROJECT_ID}/${REPO_NAME}:${TAG_NAME:-${SHORT_SHA}}'

It will perform a docker image build and push it to the project’s registry. The name of the image is derived from the project and repository name. The image tag is either:

  • the tag name
  • or the short git commit sha

As you can see, this configuration is completely generic and can be added to any container image source repository!

Google Cloud Build trigger configuration

The following Terraform snippet shows how to configure trigger a build on push:

resource "google_cloudbuild_trigger" "on-push" {
  name    = format("on-push-%s", var.repo_name)
  github {
    owner = var.repo_owner
    name  = var.repo_name
    push {
      branch = ".*"
    }
  }

  filename   = "cloudbuild.yaml"
  provider   = google-beta
}

The following Terraform snippet shows how to configure trigger a build on tag:

resource "google_cloudbuild_trigger" "on-tag" {
  name    = format("on-tag-%s", var.repo_name)
  github {
    owner = var.repo_owner
    name  = var.repo_name
    push {
      tag = "[0-9]+\\.[0-9]+\\.[0-9]+"
    }
  }

  filename   = "cloudbuild.yaml"
  provider   = google-beta
}

These trigger run on changes to the Github source repository. Checkout the documentation on creating GitHub app triggers for Google Cloud Build.

Manual build

Of course, I highly recommend against this, but to start container build process from the command line, type:

PROJECT_ID=$(gcloud config get-value core/project)
REPO_NAME=$(basename $PWD)
COMMIT_SHA=$(git rev-parse --short head)
gcloud builds submit \
  --substitutions \
    _IMAGE=gcr.io/$PROJECT_ID/$REPO_NAME:$COMMIT_SHA

Conclusion

This simple, generic Google Cloud Build config file can be used in any container image repository required in a CI/CD pipeline.

Image by TooDoTAT from Pixabay

Mark van Holsteijn is a senior software systems architect, and CTO of binx.io. He is passionate about removing waste in the software delivery process and keeping things clear and simple.
Share this article: Tweet this post / Post on LinkedIn