Skip to content

Commit 108c75f

Browse files
feat: have option for terraform_tfsec hook to only run in relevant modified directories (antonbabenko#135)
1 parent 2669065 commit 108c75f

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

README.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,22 @@ if they are present in `README.md`.
121121

122122
## Notes about terraform_tfsec hooks
123123

124-
1. `terraform_tfsec` will recurse all directories/modules.
124+
1. `terraform_tfsec` will consume modified files that pre-commit
125+
passes to it, so you can perform whitelisting of directories
126+
or files to run against via [files](https://pre-commit.com/#config-files)
127+
pre-commit flag
128+
129+
1. Example:
130+
```yaml
131+
hooks:
132+
- id: terraform_tfsec
133+
files: ^prd-infra/
134+
```
135+
136+
The above will tell pre-commit to pass down files from the `prd-infra/` folder
137+
only such that the underlying `tfsec` tool can run against changed files in this
138+
directory, ignoring any other folders at the root level
139+
125140
1. To ignore specific warnings, follow the convention from the
126141
[documentation](https://github.com/liamg/tfsec#ignoring-warnings).
127142
1. Example:

terraform_tfsec.sh

100755100644
Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,26 @@ main() {
55
initialize_
66
parse_cmdline_ "$@"
77

8-
# Don't pass any files tfsec will recurse directories anyway.
9-
tfsec "$ARGS" .
8+
# propagate $FILES to custom function
9+
tfsec_ "$ARGS" "$FILES"
10+
}
11+
12+
tfsec_() {
13+
# consume modified files passed from pre-commit so that
14+
# tfsec runs against only those relevant directories
15+
for file_with_path in $FILES; do
16+
file_with_path="${file_with_path// /__REPLACED__SPACE__}"
17+
paths[index]=$(dirname "$file_with_path")
18+
19+
let "index+=1"
20+
done
21+
22+
for path_uniq in $(echo "${paths[*]}" | tr ' ' '\n' | sort -u); do
23+
path_uniq="${path_uniq//__REPLACED__SPACE__/ }"
24+
pushd "$path_uniq" > /dev/null
25+
tfsec $ARGS
26+
popd > /dev/null
27+
done
1028
}
1129

1230
initialize_() {
@@ -41,7 +59,7 @@ parse_cmdline_() {
4159
;;
4260
--)
4361
shift
44-
# ignore any parameters, as they're not used
62+
FILES+=("$@")
4563
break
4664
;;
4765
esac
@@ -50,5 +68,6 @@ parse_cmdline_() {
5068

5169
# global arrays
5270
declare -a ARGS=()
71+
declare -a FILES=()
5372

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

0 commit comments

Comments
 (0)