How can I get current projectId inside Google Cloud Functions?
Asked Answered
N

10

21

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?

Neuter answered 5/4, 2017 at 12:46 Comment(1)
According to docs (cloud.google.com/functions/docs/env-var) GCLOUD_PROJECT is legacy and you should probably use process.env. GCP_PROJECTKendyl
N
1

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.

Neuter answered 5/4, 2017 at 15:4 Comment(0)
L
5

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
Labdanum answered 3/9, 2020 at 11:21 Comment(3)
Unfortunately, that doesn't work on newer environments, according to cloud.google.com/functions/docs/env-var#newer_runtimesSeriocomic
For newer environments you can query the internal metadata answered here: questions/30887500/retrieve-project-id-from-google-compute-engine-machineKelikeligot
Current docs say GCP_PROJECT is the current env var, and that GCLOUD_PROJECT is deprecated. Not sure if you try now, whether the emulator will work with GCP_PROJECT. Perhaps it was running an older version of the library.Empanel
T
4

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
  }
  #...
}
Tel answered 7/2, 2022 at 5:14 Comment(0)
S
3

For the Python 3.9 and newer runtimes you can use:

from google.auth import default

_, project_id = default()

This requires google-cloud-core to be installed. It works either by using the Metadata Service or from loading service account credentials.

Schriever answered 10/3, 2023 at 11:12 Comment(0)
P
2

Under Cloud Functions v2 public preview (Oct 2022), there's a section called built-in parameters that allows require of Project ID, Database URL and Storage bucket.

Presumably also Location ID ("Default GCP resource location") would be listed here, though that's not in the current documentation.

I did not get that to work.

However, this does:

const firebaseConfig = JSON.parse( process.env.FIREBASE_CONFIG );

const locationId_maybe = firebaseConfig.locationId || null;
const projectId = firebaseConfig.projectId;
const databaseURL = firebaseConfig.databaseURL;

The env.var. is always defined. locationId is defined only if there's an active Firebase project. This makes sense, since it needs access to the GCP project in the cloud.

Firebase CLI 11.15.0

Plebiscite answered 25/10, 2022 at 9:43 Comment(0)
N
1

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.

Neuter answered 5/4, 2017 at 15:4 Comment(0)
M
1

Try this.

// package.json
{
   ...
   "firebase-admin": "^11.11.0",
}

Get projectId

const options = getApp().options;
const projectId = options.projectId || (options.credential as any).projectId;
Metrology answered 8/11, 2023 at 3:27 Comment(0)
C
0

if it's an HTTP function, we can use the URL to figure out the current project and region with req.header('host')

Chromoplast answered 24/1, 2023 at 9:18 Comment(0)
G
0

If you're using Firebase, the firebase-admin package can be used to retrieve the projectId by using the following:

const admin = require('firebase-admin');

const projectId = admin.apps[0].options.credential.projectId

Gaseous answered 17/5, 2023 at 14:33 Comment(0)
W
-1

For any runtimes after node 8 you can use https://www.npmjs.com/package/gcp-metadata

const gcpMetadata = require('gcp-metadata');

export const getGCPProjectIdFromMetadata = async () => {
    const isAvailable = await gcpMetadata.isAvailable();

    if (!isAvailable) {
        return undefined;
    }

    return gcpMetadata.project('project-id');
};

This will also work across any other instances you wish to launch (such as app engine).

Wilser answered 27/10, 2021 at 20:5 Comment(0)
S
-2

When having deployed with firebase deploy there's:

functions.config().firebase.projectId
functions.config().firebase.databaseURL
functions.config().firebase.storageBucket
functions.config().firebase.locationId
Schumacher answered 11/2, 2021 at 3:58 Comment(2)
I just tried this and these variables aren't automatically set with just a firebase deploy. Do you actually need to manually set these variables for the Firebase Functions environment?Mavis
It depends on file .runtimeconfig.json inside the deployment, then these variables are known. Will not delete this answer, because it is correct; despite some people seem to fail with the basics already. One can browse the deployed files on the GCP console, below "sources".Schumacher

© 2022 - 2024 — McMap. All rights reserved.