Skip to content

Commit

Permalink
feat: have option for terraform_tfsec hook to only run in relevant mo…
Browse files Browse the repository at this point in the history
…dified directories (#135)
  • Loading branch information
nkazarian-spokeo authored Sep 1, 2020
1 parent 2669065 commit 108c75f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,22 @@ if they are present in `README.md`.

## Notes about terraform_tfsec hooks

1. `terraform_tfsec` will recurse all directories/modules.
1. `terraform_tfsec` will consume modified files that pre-commit
passes to it, so you can perform whitelisting of directories
or files to run against via [files](https://pre-commit.com/#config-files)
pre-commit flag

1. Example:
```yaml
hooks:
- id: terraform_tfsec
files: ^prd-infra/
```

The above will tell pre-commit to pass down files from the `prd-infra/` folder
only such that the underlying `tfsec` tool can run against changed files in this
directory, ignoring any other folders at the root level

1. To ignore specific warnings, follow the convention from the
[documentation](https://github.com/liamg/tfsec#ignoring-warnings).
1. Example:
Expand Down
25 changes: 22 additions & 3 deletions terraform_tfsec.sh
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,26 @@ main() {
initialize_
parse_cmdline_ "$@"

# Don't pass any files tfsec will recurse directories anyway.
tfsec "$ARGS" .
# propagate $FILES to custom function
tfsec_ "$ARGS" "$FILES"
}

tfsec_() {
# consume modified files passed from pre-commit so that
# tfsec runs against only those relevant directories
for file_with_path in $FILES; do
file_with_path="${file_with_path// /__REPLACED__SPACE__}"
paths[index]=$(dirname "$file_with_path")

let "index+=1"
done

for path_uniq in $(echo "${paths[*]}" | tr ' ' '\n' | sort -u); do
path_uniq="${path_uniq//__REPLACED__SPACE__/ }"
pushd "$path_uniq" > /dev/null
tfsec $ARGS
popd > /dev/null
done
}

initialize_() {
Expand Down Expand Up @@ -41,7 +59,7 @@ parse_cmdline_() {
;;
--)
shift
# ignore any parameters, as they're not used
FILES+=("$@")
break
;;
esac
Expand All @@ -50,5 +68,6 @@ parse_cmdline_() {

# global arrays
declare -a ARGS=()
declare -a FILES=()

[[ ${BASH_SOURCE[0]} != "$0" ]] || main "$@"

0 comments on commit 108c75f

Please sign in to comment.