Skip to content

Commit

Permalink
refactor: Trivy hook for terraform
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcelo Primo committed Aug 9, 2023
1 parent c36df86 commit 2ad1713
Showing 1 changed file with 57 additions and 14 deletions.
71 changes: 57 additions & 14 deletions hooks/trivy_terraform.sh
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 2ad1713

Please sign in to comment.