如何在jenkins中显示npm audit的结果并导致构建失败

时间:2019-10-11 15:38:51

标签: jenkins npm npm-audit

我想在ci构建中运行npm命令npm audit并以某种方式在jenkins ci构建中显示输出。

如果发现了严重漏洞,我想通过返回非零退出代码来使当前构建失败。

2 个答案:

答案 0 :(得分:1)

我不知道有任何插件可以实现此目的,但是可以进行一些手动解析(如果您使用管道)。

def output = sh script: "npm audit", returnStdout: true
def summary = output.split("\n")[-1] //get the summary from the last line
...

然后,您可以使用一些正则表达式或其他字符串操作来找到关键字符后的数字。您还可以使用archiveArtifacts将整个输出保存在构建历史记录中。

答案 1 :(得分:1)

this post的启发,我已经通过创建自定义的“编译器警告解析器”来实现了这一点;

  1. 安装Warnings Plugin
  2. 配置自定义解析器:
    管理Jenkins->配置系统->“编译器警告”部分
    名称:NPM审核分析器
    链接名称:NPM审核分析器
    趋势报告名称:检测到的漏洞
    正则表达式[\w+-]+\s+([\w+-]+)\s+([\w\.-@]+)\s+(>=\s)*([\w\.-@]+)\s+(.+?(?=http))([\w\.-@]+)\s+(.*)
    映射脚本
import hudson.plugins.warnings.parser.Warning  
import hudson.plugins.analysis.util.model.Priority

priority = Priority.HIGH;
if ( "low" == matcher.group(2)  ) {
    priority = Priority.LOW;
}
else if ( "moderate" == matcher.group(2) ) {
    priority = Priority.NORMAL;
}

String msg = "Vulnerability found in '" + matcher.group(1) + "' (" + matcher.group(6) + ") , prio: " + matcher.group(2) + " Fix: " + matcher.group(5) + " info: " + matcher.group(5);  
return new Warning('package.json', 0, 'NSP Warning', matcher.group(1), msg, priority); 
  1. 配置作业;
  2. 添加执行shell 构建步骤:
npm install  
# parseable report for 'compile warning post build step'  
npm audit --parseable >> npm_audit_report_parseable.txt || true # suppress npm audit error code
  1. 添加 [不建议使用]扫描以获取编译器警告:构建后步骤:
    '扫描工作区文件'-> 文件模式:npm_audit_report_parseable.txt
    “扫描工作区文件”-> 解析器:NPM审核分析器

(可选)您可以配置“运行状况/状态阈值”;这确定了构建失败的时间,以及何时将其标记为不稳定的时间。


另一种解决方案:使用Dependency-Check Plugin

  1. 安装Dependency-Check Plugin
  2. 配置“依赖关系检查”全局工具:
    管理詹金斯->全局工具配置->'依赖性检查'->'添加依赖性检查'
  3. 配置作业;
  4. 添加调用依赖性检查构建步骤:
    Dependency-Check安装:选择已配置的全局工具
    我还配置了其他 Arguments --scan /non/existing/dir以避免在已安装的软件包相关文件(如“ demo”,“ docs”等)中发现漏洞,因为“ dependency check plugin”会执行完整的递归文件扫描我们不需要,因为npm扫描程序已经找到了“ npm审核”结果。
  5. 添加发布依赖性检查结果生成步骤:
    XML报告:** / dependency-check-report.xml