From 87c4d9a043f8b081111b7b501c894172b1b1d4cf Mon Sep 17 00:00:00 2001
From: Bertrand Goareguer <bertrand.goareguer@gmail.com>
Date: Thu, 24 Oct 2024 06:12:18 +0000
Subject: [PATCH] refactor(trivy): run Trivy scan only once

---
 templates/gitlab-ci-docker.yml | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/templates/gitlab-ci-docker.yml b/templates/gitlab-ci-docker.yml
index 1df98cc..0197ceb 100644
--- a/templates/gitlab-ci-docker.yml
+++ b/templates/gitlab-ci-docker.yml
@@ -993,15 +993,17 @@ docker-trivy:
     # Add common trivy arguments
     # The Java DB is downloaded client-side in client/server mode (https://github.com/aquasecurity/trivy/issues/3560), so we need to specify the Java DB repository
     export trivy_opts="${trivy_opts} ${DOCKER_TRIVY_JAVA_DB_REPOSITORY:+--java-db-repository $DOCKER_TRIVY_JAVA_DB_REPOSITORY} --no-progress --severity ${DOCKER_TRIVY_SECURITY_LEVEL_THRESHOLD} ${DOCKER_TRIVY_ARGS}"
-    # GitLab format (no fail)
-    trivy ${trivy_opts} --format template --exit-code 0 --template "@/contrib/gitlab.tpl" --output reports/docker-trivy-${basename}.gitlab.json $DOCKER_SNAPSHOT_IMAGE
-    # JSON format (no fail)
-    if [[ "$DEFECTDOJO_TRIVY_REPORTS" ]]
-    then
-      trivy ${trivy_opts} --format json --exit-code 0 --output reports/docker-trivy-${basename}.native.json $DOCKER_SNAPSHOT_IMAGE
-    fi
-    # console output (fail)
-    trivy ${trivy_opts} --format table --exit-code 1 $DOCKER_SNAPSHOT_IMAGE
+
+    # Generate the native JSON report that can later be converted to other formats
+    trivy ${trivy_opts} --exit-code 1 --format json --output reports/docker-trivy-${basename}.native.json $DOCKER_SNAPSHOT_IMAGE || exit_code=$?
+
+    # Generate a report in the GitLab format
+    trivy convert --format template --template "@/contrib/gitlab.tpl" --output reports/docker-trivy-${basename}.gitlab.json reports/docker-trivy-${basename}.native.json
+
+    # console output
+    trivy convert --format table reports/docker-trivy-${basename}.native.json
+    
+    exit $exit_code
   artifacts:
     when: always
     paths:
-- 
GitLab