7

I want to pull from a private package hosted on bitbucket. Since SSH is not an option for my deploy setup, I want to access the repo using the Application Password.

So my entry in the package JSON looks like this:

"dependencies": {
    "@companyName/repository": "git+https://${$BITBUCKET_USER}:${BITBUCKET_APP_PASSWORD}@bitbucket.org/company name/repository.git",

Coding username and password hard into the repo URL works fine but when I perform yarn install as above, the environment variables are not replaced by its values.

Is there any way to use environment variables like this?

Fazle Rabbi
  • 1
  • 4
  • 16
Karl Adler
  • 15,780
  • 10
  • 70
  • 88

1 Answers1

15

You can write a preinstall hook that updates package.json with values from the environment. Luckily the order of lifecycle hooks work as prescribed using yarn.

{
  "name": "njs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "preinstall": "node preinstall.js"
  },
  "dependencies": {
      "@companyName/repository": "git+https://${$BITBUCKET_USER}:${BITBUCKET_APP_PASSWORD}@bitbucket.org/companyName/repository.git"
  },
  "author": "",
  "license": "ISC"
}

preinstall.js example:

const package = require('./package.json');
const fs = require('fs');

const {BITBUCKET_USER = 'test', BITBUCKET_APP_PASSWORD='test'} = process.env;

package.dependencies["@companyName/repository"] = package.dependencies["@companyName/repository"]
    .replace("${$BITBUCKET_USER}", BITBUCKET_USER)
    .replace("${BITBUCKET_APP_PASSWORD}", BITBUCKET_APP_PASSWORD);

fs.writeFileSync('package.json', JSON.stringify(package, null, 4));

Bonus:

How you choose to replace environment variables in preinstall.js is left to your good judgment. Yes, you can totally use ES6 template tags.

Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
  • 2
    Just verified and this works great. Great approach, just that one should not use it locally, else the file will be overwritten in local also – Tarun Lalwani Oct 16 '17 at 18:43
  • 1
    Works great, except that the username and password will be saved as text in the yarn.lock file. Another solution is to use `.git-credentials` – Hooman Sep 06 '22 at 15:59
  • @Hooman, I think no-code approaches are better. You should totally write an answer for the `.git-credentials` approach. – Oluwafemi Sule Sep 19 '22 at 07:58