How to programatically create a Cloud Run service from Node.js?

Viewed 245

I'm trying to create a new Cloud Run service from firebase functions using the googleapis client library. The following code:

  const auth = new google.auth.GoogleAuth({
    projectId,
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });
  const authClient = await auth.getClient();

  const result = await google.run({
    version: 'v1',
    auth: authClient
  }).namespaces.services.create({
    parent: `namespaces/${projectId}`,
    requestBody: {
      metadata: {
        name: 'asdf'
      },
      spec: {
        template: {
          spec: {
            containers: [
              {
                image: 'gcr.io/graph-4d1ec/graph@sha256:80c764961657d7e2fe548b3886c4662c55c9b5ac881aad5a74cce2d1f97895b8',
                env: [
                  { name: 'URL', value: url }
                ]
              }
            ]
          }
        },
        traffic: [{ percent: 100, latestRevision: true }]
      }
    }
  }, {})

Produces an error:

Error: The request has errors
    at Gaxios._request (/srv/node_modules/gaxios/build/src/gaxios.js:85:23)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

No further information is provided as to what is wrong with this request.

What am I doing wrong?

1 Answers

Most notably, the API client library you're using by default points to run.googleapis.com.

However, while using namespaces.services.create, you need a regional api endpoint, such as us-central1-run.googleapis.com. I'm not familiar with Node.js but you need to change the API endpoint from the default to this value.

You are in super luck, I just published a blog post several 5 minutes ago explaining how does gcloud run deploy work under the covers, with details on API calls, how updates are made etc. https://ahmet.im/blog/gcloud-run-deploy/ It has sample Go code linked at the end that you can study. Note that "updating" Cloud Run services has several other intricacies to understand, so make sure to check out the blog post.

Furthermore, to debug the issue you are having, I'm assuming (again I know nothing about Node.js) you might find more info in the result object that storing some error value or http response code or body.

Related