From 2ad1713501063b35fc0e0188807a8bc8d37bbbed Mon Sep 17 00:00:00 2001 From: Marcelo Primo Date: Wed, 9 Aug 2023 09:48:10 -0300 Subject: [PATCH] refactor: Trivy hook for terraform --- hooks/trivy_terraform.sh | 71 ++++++++++++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/hooks/trivy_terraform.sh b/hooks/trivy_terraform.sh index 7349ddc..31bda5e 100755 --- a/hooks/trivy_terraform.sh +++ b/hooks/trivy_terraform.sh @@ -1,22 +1,65 @@ #!/bin/env bash # +# shellcheck disable=SC2086 # allow to pass arguments as a string set -eo pipefail -# Get list of modified terraform modules -TF_DIR="$(dirname "${@}" | uniq)" +# color +RED='\033[0;31m' +GREEN='\033[0;32m' +BLUE='\033[0;34m' +ENDCOLOR='\033[0m' -# Run trivy against modified terraform modules -for dir in $TF_DIR; do +function parse_args() { + local -r args=("$@") + for arg in "${args[@]}"; do + #check if arg is a dir + if [[ -f $arg ]] || [[ -d $arg ]]; then + DIR="$DIR $(dirname "$arg")" + else + ARGS="$ARGS $arg" + fi + done +} - # Trying running trivy binary first - if [[ $(which trivy) ]]; then - # Downloading last definitions - trivy image --download-db-only - trivy config --severity MEDIUM,HIGH,CRITICAL --exit-code 1 "$dir" - else - # Running trivy docker image - docker run --rm -v "$PWD:/src:rw,Z" -w "/src" aquasec/trivy:0.44.0 config --severity MEDIUM,HIGH,CRITICAL --cache-dir /src/.pre-commit-trivy-cache --exit-code 1 "$dir" - fi +function trivy_scan() { + for dir in $DIR; do + echo -e "\n---------------------------------------" + echo "SCANNING -> $dir" + echo -e "---------------------------------------\n" -done + if [[ $trivy_bin -eq 1 ]]; then + + trivy config ${ARGS} "$dir" + else + # Running trivy docker image + docker run --rm -v "$PWD:/src:rw,Z" -w "/src" aquasec/trivy:latest config \ + --cache-dir /src/.pre-commit-trivy-cache \ + ${ARGS} "$dir" + fi + + echo -e "\n${GREEN}NO PROBLEMS FOUND!!!${ENDCOLOR}" + done +} + +# Parsing arguments +parse_args "$@" + +# removing repeated elements +DIR=$(echo "$DIR" | tr ' ' '\n' | sort -u | tr '\n' ' ') + +# Trying running trivy binary first +if which trivy > /dev/null; then + # Downloading last definitions + trivy image --download-db-only + + trivy_bin=1 + trivy_scan + +else + echo -e "${RED}Trivy binary not found!${ENDCOLOR}" + echo -e "${BLUE}Trying to run trivy docker image...${ENDCOLOR}" + + trivy_bin=0 + trivy_scan +fi