How to Update Google Cloud Run Instance using an API Axios Request
Tags: javascript, googlecloud, webdev, docker
Published: 2022-05-12 01:41:51

This tutorial is explains how to update an existing google cloud run instance using a google cloud build docker image.

First to push your docker image to Google Cloud you can run the following from your local codebase:
`gcloud builds submit --timeout=2000s --machine-type=e2-highcpu-32 --tag gcr.io/PROJECT-NAME/IMAGE-NAME .`

This will build your docker project and store it as an image in GCP container registry.

Then to deploy the image as a Google Cloud instance you can run this command:
`gcloud run deploy INSTANCE-NAME --image gcr.io/PROJECT-NAME/IMAGE-NAME --region us-east1 --platform managed --allow-unauthenticated --quiet`

Cool! Now our docker project is running in Cloud Run.

In my case I use have different code bases for different website themes and build them using docker. So I used the first command to submit all my themes to Google Cloud, but I needed a programmatic way to overwrite my cloud run instance with a new docker image when switching between themes from my frontend app.

Usually you could run the `gcloud run deploy` CLI command but I needed to convert the CLI command to an axios API request I add to a cloud function in my backend.

Here's I did it:

```
try {
async function updateTheme() {
  let token: any
  const jwtClient = new google.auth.JWT(firebaseClientEmail, "", firebaseKey, [
    'https://www.googleapis.com/auth/cloud-platform',
  ])

  await jwtClient.authorize(async function (err: any, _token: any) {
    if (err) {
      console.log("JWT ERROR: ", err)
      return err
    } else {
      token = _token.access_token.split('.')
      token = token[0] + '.' + token[1] + '.' + token[2]

      const deploySteps = [
        {
          name: 'gcr.io/cloud-builders/gcloud',
          args: [
            'run',
            'deploy',
            `${name}`,
            '--image',
            `gcr.io/${googleCloudProject}/theme-${theme}`,
            '--region',
            'us-east1',
            '--allow-unauthenticated',
            '--platform',
            'managed',
            '--quiet',
          ],
        },
      ]

      const deployRevisions = async () => {
        await axios({
          method: "post",
          url: `https://cloudbuild.googleapis.com/v1/projects/${googleCloudProject}/builds`,
          headers: {
            Authorization: `Bearer ${token}`,
          },
          data: {
            steps: deploySteps,
            timeout: "1200s",
          },
        })
          .catch(function (error: any) {
            console.log("ERROR UPDATING THEME: ", error)
            return
          })
          .then(function (response: any) {
            console.log("SUCCESSFULLY DEPLOYED THEME UPDATE")
          })
      }

      if (token) {
        deployRevisions()
      } else {
        console.log("MISSING TOKEN")
      }
    }
  })
}

await updateTheme()

} catch (e) {
    console.log("tried updating theme but something went wrong")
    return
}
```


The above chunk of code utilizes the Cloud Build API to overwrite a cloud run instance with a docker image in Google Cloud. It fetches the Google Cloud authentication code to use in the request as well.

Place it in a function and simple pass in the image name when you wish to update your cloud run instance