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 2ad1713 commit 0b25285
Showing 1 changed file with 28 additions and 20 deletions.
48 changes: 28 additions & 20 deletions hooks/trivy_terraform.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

0 comments on commit 0b25285

Please sign in to comment.