0

Is it possible to access Google Cloud Build variables such as the PROJECT_ID as part of a gcp-build script in a Google App Engine Standard Node.js custom build step?

In my testing, the gcp-build script is able to get an application default credential and from what I recall, the auth library has multiple different approaches that it falls back through to get the credential (eg. environment variables, well-known file, metadata service, etc).

I checked the environment variables via process.env and didn't see any variables relevant to the question. I skipped the well-known file approach and tried the metadata service and was able to get the project ID from the metadata service, but I'm curious what the recommended approach is or if there is a better way to access variables like the project ID.

Josh Lyon
  • 399
  • 5
  • 11
  • 1
    I did not know that this feature existed until I read your question ;-) I suspect that using the metadata service is the best approach (and you know it works). That said, is it curious that you're not getting the default set of environment variables provided by Cloud Build. I'll ping a colleague and see whether they can help. – DazWilkin Aug 01 '19 at 04:01
  • 1
    I deployed the sample app. `gcp-build` appears to configure an existing Cloud Build step (`builder`). I suspect (!?) that while your process is indeed running under Cloud Build, it's constrained by the `builder` step that does not expose environment variables into it. It's likely a good feature request (see https://issuetracker.google.com). – DazWilkin Aug 01 '19 at 04:28

1 Answers1

2

It seems this is not possible yet. Apart from the metadata service, you could also do this:

You can insert a placeholder, "$VAR", in the "gcp-build" script in package.json, and substitute it using sed with the value you need, in this case PROJECT_ID, that you can get with gcloud:

sed -i "s/\$VAR/$(gcloud config get-value project)/" package.json

So a package.json line like

"gcp-build": "echo $VAR"

would become, if your project is "op-project",

"gcp-build": "echo op-project"

You then can make an alias or little script to always run this when deploying.

asbovelw
  • 552
  • 2
  • 9
  • Thanks for the suggestion! That's definitely a creative way of going about things. Calling `gcloud` via `exec` is one of the methods used in the `google-auth-library`, so I suppose it could be done within the Node script as well. Reference: https://github.com/googleapis/google-auth-library-nodejs/blob/f7a40464f404d66068faa5b466d52355afb298a5/src/auth/googleauth.ts#L581 – Josh Lyon Aug 02 '19 at 16:09
  • What Node script? Do you mean using a Node script instead of a bash one for making the substitution? – asbovelw Aug 05 '19 at 11:48
  • Yes, in my head it was implied that since it was a Node Standard project that the `gcp-build` step would also be a Node script, but to your point it could also be a shell script! – Josh Lyon Aug 06 '19 at 20:21