简体   繁体   中英

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 ?

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 )

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM