Get a (pseudo) sequential build number in Google Cloud Build
Google cloud build’s substitutions do not include a sequential build number. One way to get a number that will always increase with commits is to count the number of commits using git rev-list --count master
.
Cloud build does a shallow check-out and therefore the above mentioned command always returns ‘1’. To solve this we unshallow the checked-out repository using git fetch --unshallow
.
To use this number across build steps we will write the value to a file in the build workspace and read it again using normal bash utilities. Additionally to apply semantic versioning we can use custom substitutions, “_MAJOR”, “_MINOR”, “_PATCH”, which will be defined in the build trigger and incremented manually as needed.
To accomplish all of this we will use a different entrypoint to some of the cloud builders. This is what your cloudbuild.yaml
may look like to do a Docker build:
This cloudbuild.yaml
script writes the number of commits, with the semantic version, to a file called “IMAGE_TAG” (if you’re not building a Docker image you may just call it “VERSION”), and then it does a cat IMAGE_TAG
wherever that value is reused. To do this the bash entrypoint is used. An example of what this value may look like is “1.2.1.164”.