简体   繁体   English

package.json中的多个任务的一个预处理

[英]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 . 我正在使用Terraform进行项目,我在package.json有两个任务来启动terraform planterraform apply

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

For both of these commands, I need to perform a terraform get first. 对于这两个命令,我需要首先执行terraform get I would like to have just one pretask for both of them. 我想为他们两个做一个pretask

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 ? 有没有办法NPMYarn来实现这个目的? 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. 这是另一个假装"tf:*" prehook的选项。 Only for obscure cryptic npm ninjas and not recomended: 只是为了模糊神秘的npm忍者,而不是推荐:

"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 ) (使用npm run tf:plan或直接使用任何参数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: 您可以将package.json中的事件直接绑定到节点脚本,在节点脚本中,您可以通过以下方式执行terraform命令和公共代码:

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: 您也可以使用一个接受参数的单节点脚本来指定要执行的terraform任务,在脚本中定义公共代码,然后根据参数执行正确的命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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