@@ -25,6 +25,7 @@ function common::initialize {
2525# Globals (init and populate):
2626# ARGS (array) arguments that configure wrapped tool behavior
2727# HOOK_CONFIG (array) arguments that configure hook behavior
28+ # INIT_ARGS (array) arguments for `terraform init` command
2829# FILES (array) filenames to check
2930# Arguments:
3031# $@ (array) all specified in `hooks.[].args` in
@@ -34,6 +35,8 @@ function common::parse_cmdline {
3435 # common global arrays.
3536 # Populated via `common::parse_cmdline` and can be used inside hooks' functions
3637 ARGS=() HOOK_CONFIG=() FILES=()
38+ # Used inside `common::terraform_init` function
39+ INIT_ARGS=()
3740
3841 local argv
3942 argv=$( getopt -o a:,h: --long args:,hook-config: -- " $@ " ) || return
@@ -51,6 +54,11 @@ function common::parse_cmdline {
5154 HOOK_CONFIG+=(" $1 ;" )
5255 shift
5356 ;;
57+ -i | --init-args)
58+ shift
59+ INIT_ARGS+=(" $1 " )
60+ shift
61+ ;;
5462 --)
5563 shift
5664 # shellcheck disable=SC2034 # Variable is used
@@ -230,3 +238,34 @@ function common::colorify {
230238
231239 echo -e " ${COLOR}${TEXT}${RESET} "
232240}
241+
242+ # ######################################################################
243+ # Run terraform init command
244+ # Arguments:
245+ # command_name (string) command that will tun after successful init
246+ # dir_path (string) PATH to dir relative to git repo root.
247+ # Can be used in error logging
248+ # Globals (init and populate):
249+ # INIT_ARGS (array) arguments for `terraform init` command
250+ # Outputs:
251+ # If failed - print out terraform init output
252+ # ######################################################################
253+ function common::terraform_init {
254+ local -r command_name=$1
255+ local -r dir_path=$2
256+
257+ local exit_code=0
258+ local init_output
259+
260+ if [ ! -d .terraform ]; then
261+ init_output=$( terraform init -backend=false " ${INIT_ARGS[@]} " 2>&1 )
262+ exit_code=$?
263+
264+ if [ $exit_code -ne 0 ]; then
265+ common::colorify " red" " 'terraform init' failed, '$command_name ' skipped: $dir_path "
266+ echo -e " $init_output \n\n"
267+ fi
268+ fi
269+
270+ return $exit_code
271+ }
0 commit comments