Skip to content

Instantly share code, notes, and snippets.

@justmiles
Created July 22, 2021 18:21
Show Gist options
  • Save justmiles/cafad8d94e008617f38963cc356325b3 to your computer and use it in GitHub Desktop.
Save justmiles/cafad8d94e008617f38963cc356325b3 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
IN_USE=$(mktemp)
ALL_FILES=$(mktemp)
function find_module() {
dir=$(realpath $1)
find "$dir" -maxdepth 1 -type f -name '*.tf' | while read file; do
echo "${file}" >>$IN_USE
grep -o "\s*source\s*=.*" $file | grep -v git | awk '{print $3}' | sed 's/"//g' | while read module; do
if [ -d "${1}/${module}" ]; then
find_module "${1}/${module}"
fi
done
done
}
find workspaces -mindepth 2 -maxdepth 2 -type d | while read workspace; do
find_module $workspace
done
find . -mindepth 2 -type f -name '*.tf' | grep -v ".terraform" | xargs realpath | sort | uniq >$ALL_FILES
comm <(cat $IN_USE | xargs realpath | sort | uniq) $ALL_FILES -3 | sort | sed 's/ //' | uniq | xargs -I % dirname % | uniq | xargs -I % rm -rf %
rm -rf $IN_USER $ALL_FILES
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment