Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save viatcheslavmogilevsky/94c9d438181e4dfb4238a22f3dc7ab91 to your computer and use it in GitHub Desktop.

Select an option

Save viatcheslavmogilevsky/94c9d438181e4dfb4238a22f3dc7ab91 to your computer and use it in GitHub Desktop.
#!/bin/bash -e
TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
declare -a iaac_repos=("$HOME/acme-corp/iaac-repo-01"
"$HOME/acme-corp/iaac-repo-02"
)
LOCKED_PROVIDER_VERSIONS="{}"
for iaac_repo in "${iaac_repos[@]}"; do
for hcl_lock_file in $(git -C $iaac_repo ls-files | grep -F ".terraform.lock.hcl"); do
CURRENT_PROVIDER_VERSIONS=$(echo "$iaac_repo/$hcl_lock_file" | xargs hcl2json | jq -r -M '.provider | to_entries | map({key: .key, value: [.value[] | .version]}) | from_entries')
LOCKED_PROVIDER_VERSIONS=$(echo "$LOCKED_PROVIDER_VERSIONS" | jq --argjson to_merge_with "$CURRENT_PROVIDER_VERSIONS" '
def array_merge(a; b):
if (a | type) == "array" and (b | type) == "array" then
a + b | unique
else
b
end;
(
to_entries
+
($to_merge_with | to_entries)
)
| reduce .[] as $item ({};
. + {
($item.key): (
if has($item.key) then
array_merge(.[$item.key]; $item.value)
else
$item.value
end
)
}
)
'
)
done
done
LOCKED_PROVIDER_PATHS=$(echo $LOCKED_PROVIDER_VERSIONS | jq -r '. | to_entries[] | .key as $key | .value[] | "./\($key)/\(.)"')
CACHED_PROVIDER_VERSIONS=$(cd "$TF_PLUGIN_CACHE_DIR"; find . -mindepth 4 -maxdepth 4 -type d)
TO_DELETE="$(comm -23 <(echo "$CACHED_PROVIDER_VERSIONS" | sort) <(echo "$LOCKED_PROVIDER_PATHS" | sort))"
for td_item in ${TO_DELETE[@]}; do
echo "Delete ${TF_PLUGIN_CACHE_DIR}/${td_item} (yes/no/quit)?"
read -r line
if [[ $line == "quit" ]]; then
echo "Quitting the loop..."
break
fi
if [[ $line == "yes" ]]; then
echo "Deleting ${TF_PLUGIN_CACHE_DIR}/${td_item}..."
rm -r "${TF_PLUGIN_CACHE_DIR}/${td_item}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment