From 0b252856d458f0f6f9099afdfc2cd802f00d2a87 Mon Sep 17 00:00:00 2001 From: Marcelo Primo Date: Wed, 9 Aug 2023 10:38:52 -0300 Subject: [PATCH] refactor: Trivy hook for terraform --- hooks/trivy_terraform.sh | 48 +++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/hooks/trivy_terraform.sh b/hooks/trivy_terraform.sh index 31bda5e..670eb95 100755 --- a/hooks/trivy_terraform.sh +++ b/hooks/trivy_terraform.sh @@ -10,10 +10,17 @@ GREEN='\033[0;32m' BLUE='\033[0;34m' ENDCOLOR='\033[0m' +# Validate Dependencies +if ! command -v trivy &> /dev/null && ! command -v docker &> /dev/null; then + echo -e "${RED}Error: Neither 'trivy' binary or 'docker' found!${ENDCOLOR}" + exit 1 +fi + +# Parsing arguments 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 @@ -22,44 +29,45 @@ function parse_args() { done } +# Scanning directories function trivy_scan() { + local trivy_bin + + # Trying running trivy binary first + # and downloading latest definitions + if command -v trivy &> /dev/null; then + trivy image --download-db-only + trivy_bin=1 + + else + echo -e "${RED}Trivy binary not found!${ENDCOLOR}" + echo -e "${BLUE}Trying to run trivy docker image...${ENDCOLOR}" + trivy_bin=0 + + fi + for dir in $DIR; do echo -e "\n---------------------------------------" echo "SCANNING -> $dir" echo -e "---------------------------------------\n" 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 +# 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 +trivy_scan