How to access variable from specific environment with Grunt

545 Views Asked by At

I'm using the following Grunt configuration to run some commands on the test or production server:

...
secret_test: grunt.file.readJSON('./deploy/test.json'),
secret_prod: grunt.file.readJSON('./deploy/prod.json'),
sshconfig: {
  test: {
    host: '<%= secret_test.host %>',
    port: '<%= secret_test.port %>',
    username: '<%= secret_test.username %>',
    password: '<%= secret_test.password %>',
    path: '<%= secret_test.path %>',
    createDirectories: true
  },
  prod: {
    host: '<%= secret_prod.host %>',
    port: '<%= secret_prod.port %>',
    username: '<%= secret_prod.username %>',
    password: '<%= secret_prod.password %>',
    path: '<%= secret_prod.path %>',
    createDirectories: true
  },
},
sshexec: {
  uptime: {
    command: 'uptime', // working fine
  },
  ls: {
     command: '???' // I'd like to list the content of the path provided (test or prod)
  },
  ...
},

secret_test and secret_prod have the following format:

{
"host" : "MY_SERVER",
"port": 22,
"path" : "SOME_PATH",
"username" : "USERNAME",
"password": "PWD"

}

To run the 'ls' task on the test env, I use:

grunt ls --config test

Path are different in test and prod, how can I access the value of the path linked to the config I specified ?

1

There are 1 best solutions below

0
On BEST ANSWER

I would use the grunt-env plugin With grunt env:

env:
 dev:
  host: ...
  port: ...
 prod:
  host: ...
  port: ...

Then just register the tasks...

grunt.registerTask('dev', 'env:dev lint server watch');
grunt.registerTask('build', 'env:build lint other:build:tasks');

You can access the variables through

process.env.VARIABLE_NAME