Want to make sure all the variables declared in a terraform module are actually used in the code?

This code lists all variables used in each of the sub-directories containing terraform code.

It started off as a one-liner but, as usual, the code to make it look pretty is bigger than the main functional code!

#!/usr/bin/env bash

set -euo pipefail

default_ul_char=-

main() {
  process
}

print_underlined () {
  local text="$1" ; shift
  local ul_char
  if [[ -n ${1:-} ]] ; then
    ul_char="$1" ; shift
  else
    ul_char=$default_ul_char
  fi
  printf '%s\n%s\n' "$text" "${text//?/$ul_char}"
}

process() {
  # loop over all directories
  while read -r dir ; do
    pushd "$dir" >/dev/null
    echo
    print_underlined "$dir" 
    # get a unique list of variables used in all .tf files in this directory
    sort -u < <(
      perl -ne 'print "$1\n" while /var\.([\w-]+)/g' ./*.tf
    )
    popd > /dev/null
  done < <(
    # get a unique list of directories containing terraform files
    # starting in the present working directory
    sort -u < <(
      find . -name '*.tf' -exec dirname {} \;
    )
  )
}

main "$@"

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

This site uses Akismet to reduce spam. Learn how your comment data is processed.