Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One pretask for multiple tasks in package.json

I am using Terraform for a project and I got two tasks in my package.json to launch terraform plan and terraform apply.

"scripts": {
    "tf:apply": "terraform apply",
    "tf:plan": "terraform plan"
}

For both of these commands, I need to perform a terraform get first. I would like to have just one pretask for both of them.

I tried to use:

"scripts": {
    "pretf:*": "terraform get",
    "tf:apply": "terraform apply",
    "tf:plan": "terraform plan"
}

But it doesn't work.

Is there any way to achieve this using NPM or Yarn only ? Or am I forced to write the exact same pretask for both of these tasks ?

like image 476
Erazihel Avatar asked Apr 28 '17 11:04

Erazihel


2 Answers

I usually go like this:

"scripts": {
    "tf:get": "terraform get",
    "tf:apply": "npm run tf:get && terraform apply",
    "tf:plan": "npm run tf:get && terraform plan"
}

This is another option which fakes a sort of "tf:*" prehook. Only for obscure cryptic npm ninjas and not recomended:

"scripts": {
    "pretf": "terraform get",
    "tf": "terraform",
    "tf:apply": "npm run tf -- apply",
    "tf:plan": "npm run tf -- plan"
}

(Use it with npm run tf:plan or directly with any argument npm run tf -- whathever)

like image 161
Andrea Carraro Avatar answered Oct 05 '22 08:10

Andrea Carraro


Have you tried to manage it directly using node?

You can bind the events inside your package.json directly to node scripts and inside the node scripts you can execute your terraform commands and your common code in this way:

var exec = require('child_process').exec;
var cmd = 'terraform apply';

// common code

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

You could also just use one single node script accepting a parameter to specify which terraform task to execute, define your common code inside the script, and then execute the right command depending on the parameter:

"scripts": {
    "tf:apply": "node myscript.js --param=apply",
    "tf:plan": "node myscript.js --param=plan"
}

Then inside node you can access your param in this way:

console.log(process.argv.param);
like image 22
quirimmo Avatar answered Oct 05 '22 09:10

quirimmo