Search code examples
google-cloud-functionstwiliogoogle-cloud-tasks

Get a Cloud Function name from the Cloud Function itself


When sending SMS to Twilio, Twilio sends several requests to a specified URL to give a status of that SMS delivery through webhooks. I want to make this callback asynchronous, so I developed a Cloud Function that sends a representation of the request to a Cloud Task that itself reach a dedicated endpoint of my app that recreate and simulate the Twilio request internally.

Twilio signs his requests using:

  • my twilio account's secret key
  • the absolute URL that it reaches out
  • and the body of his request

So on my backend, I should know which endpoint Twilio reached out initially. I want to do it inside the Cloud Function, and I want to do it programmatically because this "asynchronous webhook" is also used when people answers to SMS.

The current URL of my webhook has the following format:

https://<location>-<project>.cloudfunctions.net/<cloud function name>/<some SMS uuid>

The current payload sent to my Cloud Task is the following:

absoluteUri: req.protocol + '://' + req.hostname + req.originalUrl,
relativeUri: req.originalUrl,
queryParams: req.query,
headers: req.headers,
body: req.body,

The problem is that req.originalUrl do not contain the full URI, my absoluteUri is currently:

https://<location>-<project>.cloudfunctions.net/<some SMS uuid>

So here is my question: inside a Cloud Function, is there a way to get its name programmatically?


Solution

  • I'm using python 3.9 and get the Cloud Function name from the curiously named "K_SERVICE" environment variable.

    import os
    print("Current Cloud Function Name {}".format(os.environ.get('K_SERVICE')))
    

    Enjoy them while you can, Google are removing more and more useful environment variables with every new language version. https://cloud.google.com/functions/docs/configuring/env-var#python_37_and_go_111