You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins Pipeline中生成有效的Trivy HTML扫描报告?

Jenkins Pipeline中Trivy JSON转HTML空文件问题排查与修复

核心问题排查方向

先从这几个关键点逐一验证:

  • JSON报告有效性:如果原始JSON报告为空或格式错误,渲染出的HTML必然是空的
  • 模板文件路径:确认html.tpl存在于Jenkins工作区,且路径引用正确
  • Trivy渲染命令:官方要求的模板引用格式是否正确,有没有遗漏关键符号
  • 工作区权限:Jenkins代理是否有读写工作区文件的权限

具体修复步骤

1. 先验证JSON报告完整性

在扫描阶段后加一步验证,确保JSON文件内容正常:

sh 'echo "JSON报告内容检查:"'
sh 'jq . frontend-trivy-noncritical.json || echo "JSON文件格式错误或为空"'

如果输出提示无效JSON,先解决扫描阶段的问题,确保Trivy能生成完整的扫描结果。

2. 确认模板文件存在

在转换阶段前检查模板是否在工作区:

sh 'ls -la html.tpl || echo "模板文件html.tpl不存在,请确认下载路径"'

如果模板不在工作区,直接在Pipeline里加入下载步骤:

sh 'curl -O https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/html.tpl'

3. 使用正确的Trivy渲染命令

Trivy转HTML有两种方式,选适合你的场景:

方式一:直接扫描并生成HTML(跳过单独JSON步骤)

sh 'trivy image --format template --template "@html.tpl" -o frontend-trivy-noncritical-report2.html my-frontend-app:latest'

方式二:基于已有的JSON报告转换

sh 'trivy convert --format html --template "@html.tpl" -o frontend-trivy-noncritical-report2.html frontend-trivy-noncritical.json'

⚠️ 注意:模板路径前的@符号不能省略,这是Trivy识别模板文件的关键标记。

4. 检查权限与版本

  • 确保Jenkins代理运行用户对工作区有读写权限,必要时添加权限修正:
    sh 'chmod 644 frontend-trivy-noncritical.json'
    
  • 升级Trivy到最新版本,旧版本可能存在模板渲染或convert命令的兼容性问题:
    sh 'trivy --version'
    

修正后的完整Pipeline示例

pipeline {
    agent any

    stages {
        stage('构建Docker镜像') {
            steps {
                script {
                    sh 'docker build -t my-frontend-app:latest .'
                }
            }
        }

        stage('Trivy扫描生成JSON报告') {
            steps {
                script {
                    sh 'trivy image --format json -o frontend-trivy-noncritical.json my-frontend-app:latest'
                    // 验证JSON报告
                    sh 'echo "检查JSON报告:"'
                    sh 'jq . frontend-trivy-noncritical.json || echo "JSON文件异常"'
                }
            }
        }

        stage('转换为HTML报告') {
            steps {
                script {
                    // 确保模板存在
                    sh 'ls -la html.tpl || (echo "下载模板文件" && curl -O https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/html.tpl)'
                    // 执行转换
                    sh 'trivy convert --format html --template "@html.tpl" -o frontend-trivy-noncritical-report2.html frontend-trivy-noncritical.json'
                    // 验证HTML生成
                    sh 'ls -la frontend-trivy-noncritical-report2.html && echo "HTML报告生成成功"'
                }
            }
        }

        stage('归档报告') {
            steps {
                archiveArtifacts artifacts: 'frontend-trivy-*.html,frontend-trivy-*.json', fingerprint: true
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Achebe Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 20:19:54