Using NPM token from Google Secret Manager during Cloud Build process

Viewed 527

Can Google Cloud Build use an NPM token during the install process?

I'm using a private NPM package across applications and I know we can place the token within an .npmrc file

//registry.npmjs.org/:_authToken=<YOUR_AUTH_TOKEN>

But I would like to keep the token out of the codebase(s) and use SM for what it's for.

But this doesn't seem possible and the docs do not seem to cover this.

2 Answers

Meanwhile, posting the solution proposed by sethvargo and guillaume blaquiere for visibility.

You can set the token value as an environment variable, NPM_TOKEN. In that case, you can use the native Cloud Build + Secret Manager integration to inject the value: cloud.google.com/build/docs/securing-builds/use-secrets

If the NPM_TOKEN solution doesn't work, you can still use the Secret Manager and Cloud Build to load your token, write your .npmrc file with a script and then run your build.

I had to get experienced help for Secret Manager for this and it still took over 20 hours.

Assuming you possess general knowledge of GCP and Secret Manager and have your NPM token on-hand (found at npmjs.com/settings/USERNAME/tokens)

  1. Create a Secret Manager secret named NPM_TOKEN with its value being the private NPM package's automation token
  2. Within the cloudbuild.yaml build process create an .npmrc
steps:
  - name: bash
    args: ['-c', 'echo //registry.npmjs.org/:_authToken=$$NPM_TOKEN > .npmrc'] <-- main takeaway
    secretEnv: ['NPM_TOKEN']
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    args: ['gcloud', 'app', 'deploy']
availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/NPM_TOKEN/versions/latest
      env: 'NPM_TOKEN'

Now the cloud build process has an NPM_TOKEN value to pull in the private NPM package.

Related