I was looking for a simple setup like Cloud Run, which linked to my Github repository and continuously built and deployed without any hassle. Let's see how you can accomplish this with Cloud Build.
First, you need to grant access to your Github repo to the Google Cloud Build Github app. This can be done in Github app authorizations section.
The next step will be to create a Cloud Build Trigger. You can find this option in Google cloud console.
Configure the cloud build to your liking. Set the Source to your Github repository.
Next, we need to define what to do when the repository is updated. This can be defined in different ways, but I have selected the Inline cloud build configuration YAML option.
Now click on Open Editor to change the configuration YAML file. I am giving the code below directly, then I will explain what is happening.
steps: - name: 'node:16-slim' args: - '-c' - | npm ci && npm run build && mkdir -p /workspace/dist && cp package.json /workspace/dist/package.json && cp -r lib /workspace/dist entrypoint: bash - name: gcr.io/cloud-builders/gcloud-slim args: - functions - deploy - <function_name> - '--region' - asia-south2 - '--trigger-topic' - <pub_sub_topic_name> - '--timeout' - 10s - '--memory' - 128mb - '--runtime' - nodejs16 - '--entry-point' - <entrypoint_name> - '--max-instances' - '2' - '--source' - /workspace/dist
In the first step, we are using the Node 16 image to install node dependencies, then building the repository using
npm run build. The main point to note here is that we are copying built artifacts to the
/workspace is a special path in Cloud Build, where different steps can keep files to share with other steps.
In the second step, we are using gcloud to deploy our function from the
/workspace/dist directory, with the
--source flag. Other options can be configured to meet the needs of your function.
Finally, save this build trigger. Now you will have a continuously deployed cloud function written in TypeScript.