Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get current projectId inside Google Cloud Functions?

The question is simple. I need projectId in order to establish connection insde Google Cloud Function. I found the documentation where it said, that projectId is optional parameter and will be checked from GCLOUD_PROJECT, but on deployed function it didn't work.

So it is the question now how can I get the projectId env variable in order to pass it as argument for Datastore connection instance, or what should be done to not pass this id and establish connection with datastore inside Google Cloud Function?

Update 1

I found that I actually can get variable from process.env.GCLOUD_PROJECT, just like any other env.variable. But, know is the last question, is it actually possible to use @google-cloud/datastore without any configuration object?

like image 811
QuestionAndAnswer Avatar asked Apr 05 '17 12:04

QuestionAndAnswer


3 Answers

You can get project ID as const projectId = process.env.GCP_PROJECT. But for some reason the environmet variable "GCP_PROJECT" is not set when running the emulator. Instead the deprecated variable name "GCLOUD_PROJECT" is the one to select. So you might try them both.

const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT
like image 114
Mohammad Hazara Avatar answered Sep 17 '22 15:09

Mohammad Hazara


As I wrote in update 1 we can get all the information about environment from the process.env variable.

And the second question about configuration object for @google-cloud/datastore, it actually can work without any options. It will trying to fetch all required parameters from environment variables. So, it didn't work beacuase of error in my code.

like image 22
QuestionAndAnswer Avatar answered Sep 20 '22 15:09

QuestionAndAnswer


The answer depends on which runtime you are using. If your using Python 3.7 and Go 1.11 you are in luck. Use

process.env.GCP_PROJECT

If using any of the new runtimes, bad luck, either access the metadata server, or google suggests

Note: If your function/app requires one of the environment variables from an older runtime, you can set the variable when deploying your function. For example:

gcloud functions deploy envVarMemory \
--runtime nodejs10 \
--set-env-vars FUNCTION_MEMORY_MB=2Gi \
--memory 2Gi \
--trigger-http

If using terraform:

resource "google_cloudfunctions_function" "my-function" {
  name        = "my-function"
  runtime     = "nodejs16"
  environment_variables = {
    GCP_PROJECT = var.project_id
  }
  #...
}
like image 28
intotecho Avatar answered Sep 20 '22 15:09

intotecho