Pm2: How to set TOP secret environment variables in ecosystem.config.js ?

Created on 13 Oct 2019  路  7Comments  路  Source: Unitech/pm2

Since it is too risky to commit ecosystem.config.js with secret environment variables to a repository then how I could set environment variables coming from a CI like gitlab or CircleCI ?

Example:

module.exports = {
  apps: [
    {
      name: 'app-name',
      script: 'service.js',
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      env_staging: {
        TOP_SECRET_ENV_VARIABLE: process.env.TOP_SECRET_ENV_VARIABLE,
      }
    }
  ],

  deploy: {
    production: {
      user: 'xxxxxx',
      host: 'xxxxxx',
      ref: 'origin/master',
      repo: 'xxxxxx',
      path: 'xxxxxx',
      'post-deploy':
        'npm install && pm2 reload ecosystem.config.js --env production'
    },
  }
};
stale

All 7 comments

Great question, I'm also curious!

I'm also trying to do it, but not successful.

Did you get it working @debianw ?

@marceloavf I gave up with ecosystem.config.js, it is so painful and don't support TOP secret environment variables.

I did my own recipe

@debianw do you mind sharing that recipe?

I solved it by storing the key in the server manually and requiring the key in ecosystem.config.js file
Example

  • /etc/config/apikey or store in the directory you wish.
  • The file api-key will contain Top secret key.
    Now in ecosystem.config.js file
//ecosystem.config.js
const  fs = require('fs');
const  path = require('path');
const  pathToSecretKey = path.join('/etc', 'dir-name', 'api-key');
const  secretKey = () => {
  try {
    const  readSecretKey = fs.readFileSync(pathToSecretKey, 'utf8');
    return  readSecretKey.trim(); //triming the string to omit any trainling
  } catch (error) {
    console.error(`Error reading Secret Key ${error}`);
    console.log('Exiting prosses with error status code 1');
    process.exit(1);
  }
};

module.exports = {
    apps: [{
        name:  'site-api',
        script:  './index.js',
        instances:  0,
        exec_mode:  'cluster',
        autorestart:  true,
        max_memory_restart:  '1G',
        env: {
          NODE_ENV:  'production',
          SECRET_KEY:  secretKey()
        }
      }]
};

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

I have a .env file (that holds my secrets) that I would love to have on my server, and I see that pm2 created a /shared folder when deploying, but I don't see how to use files in that folder?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rajendar38 picture rajendar38  路  3Comments

mario-mui picture mario-mui  路  3Comments

FujiHaruka picture FujiHaruka  路  3Comments

webchaz picture webchaz  路  3Comments

phra picture phra  路  3Comments