Continuous Deployment of Google Cloud Functions Written with TypeScript

Posted on Wed Jun 08 2022

Introduction

Recently, I was trying to continuously deploy a Google Cloud Function, triggered with Cloud Pub/Sub. But the catch was that this function was written in TypeScript. Every article I could find was either using plain JavaScript or recommending cloning the Github repository with Google Cloud Source. There was also the choice of keeping compiled code in the repository.

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.

Using 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.

connect-github-repo

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.

build-config

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.

1steps:
2  - name: 'node:16-slim'
3    args:
4      - '-c'
5      - |
6        npm ci &&
7        npm run build &&
8        mkdir -p /workspace/dist &&
9        cp package.json /workspace/dist/package.json &&
10        cp -r lib /workspace/dist
11    entrypoint: bash
12  - name: gcr.io/cloud-builders/gcloud-slim
13    args:
14      - functions
15      - deploy
16      - <function_name>
17      - '--region'
18      - asia-south2
19      - '--trigger-topic'
20      - <pub_sub_topic_name>
21      - '--timeout'
22      - 10s
23      - '--memory'
24      - 128mb
25      - '--runtime'
26      - nodejs16
27      - '--entry-point'
28      - <entrypoint_name>
29      - '--max-instances'
30      - '2'
31      - '--source'
32      - /workspace/dist
33

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/dist directory.

/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.