From 51f8ca0e53b1955a6917047b3d64d5b97518c4a3 Mon Sep 17 00:00:00 2001
From: Bertrand Goareguer <bertrand.goareguer@gmail.com>
Date: Wed, 23 Oct 2024 14:20:52 +0000
Subject: [PATCH] refactor(trivy): run Trivy scan only once

---
 templates/gitlab-ci-python.yml | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/templates/gitlab-ci-python.yml b/templates/gitlab-ci-python.yml
index 41665b4..13f66d3 100644
--- a/templates/gitlab-ci-python.yml
+++ b/templates/gitlab-ci-python.yml
@@ -1295,15 +1295,18 @@ py-trivy:
           log_warn "The ./requirements.txt file does not match the ./reports/requirements.txt file generated via pip freeze. Make sure to include all dependencies with pinned versions in ./requirements.txt and re-commit the file."
         fi
       fi
-      if [ $($python_trivy fs ${PYTHON_TRIVY_ARGS} --format table --exit-code 0 ./reports/ 2>&1 | grep -ic "Number of language-specific files[^0-9]*0$" ) -eq 1 ]; then
+
+      # Generate the native JSON report that can later be converted to other formats
+      $python_trivy fs ${PYTHON_TRIVY_ARGS} --format json --list-all-pkgs --output reports/py-trivy.trivy.json --exit-code 1 ./reports/ > ./reports/trivy.log 2>&1 || exit_code=$?
+      cat ./reports/trivy.log
+      if [ $(grep -ic "Number of language-specific files[^0-9]*0$" ./reports/trivy.log) -eq 1 ]; then
         log_error "Could not find a file listing all dependencies with their versions."
         exit 1
       fi
-      if [[ "$DEFECTDOJO_TRIVY_REPORTS" ]]
-      then
-        $python_trivy fs ${PYTHON_TRIVY_ARGS} --exit-code 0 --list-all-pkgs --format json --output reports/py-trivy.trivy.json ./reports/
-      fi
-      $python_trivy fs ${PYTHON_TRIVY_ARGS} --exit-code 1 --format table ./reports/
+      rm ./reports/trivy.log
+      # console output
+      $python_trivy convert --format table reports/py-trivy.trivy.json
+      exit $exit_code
   artifacts:
     name: "$CI_JOB_NAME artifacts from $CI_PROJECT_NAME on $CI_COMMIT_REF_SLUG"
     expire_in: 1 day
-- 
GitLab