forked from fugue/regula
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regula
executable file
·64 lines (55 loc) · 1.7 KB
/
regula
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/bash
set -o nounset -o errexit -o pipefail
# Basic command line argument handling.
if [[ $# -lt 1 ]]; then
1>&2 echo "Usage: $0 TERRAFORM_DIR [REGO_PATHS..]"
1>&2 echo ""
1>&2 echo "Regula is a little wrapper to run Rego validations on terraform"
1>&2 echo "files. It is meant to be used as a pre-flight check before"
1>&2 echo "deployment."
exit 1
fi
TERRAFORM_DIR="$1"
shift 1
REGO_PATHS=("$@")
# Setting this variable will cause terraform to print a little less information
# on what to do next.
TF_IN_AUTOMATION=true
# Allow overriding terraform version.
TERRAFORM="${TERRAFORM:-terraform}"
# Hide the output of a command only if it succeeds.
function silently {
local log="$(mktemp -t silently.XXXXXXX)"
local exit_code=""
1>&2 echo "${1+$@}"
${1+"$@"} >"$log" 2>&1 || exit_code=$?
if [[ ! -z $exit_code ]]; then
1>&2 echo "${1+$@} failed; output ($log):"
1>&2 cat "$log"
exit $exit_code
fi
rm "$log"
}
# Temporary files.
TERRAFORM_PLAN="$(mktemp -t plan.XXXXXXX)"
TERRAFORM_PLAN_JSON="$(mktemp -t plan.json.XXXXXXX)"
function cleanup {
rm -f "$TERRAFORM_PLAN" "$TERRAFORM_PLAN_JSON"
}
trap cleanup exit
# Run terraform to obtain the plan.
(cd "$TERRAFORM_DIR" &&
silently "$TERRAFORM" init &&
silently "$TERRAFORM" plan -refresh=false -out="$TERRAFORM_PLAN" &&
"$TERRAFORM" show -json "$TERRAFORM_PLAN" >"$TERRAFORM_PLAN_JSON")
# Prepend `-d` to every argument because `opa` expects to see many `-d`
# arguments.
D_REGO_PATHS=()
for p in "${REGO_PATHS[@]}"; do
D_REGO_PATHS+=('-d')
D_REGO_PATHS+=("$p")
done
# Finally, run OPA on the result to get out our report.
opa eval -i "$TERRAFORM_PLAN_JSON" \
"${D_REGO_PATHS[@]}" \
'data.fugue.regula.report'