Skip to content

Instantly share code, notes, and snippets.

@JeffreyVdb
Last active June 7, 2023 09:43
Show Gist options
  • Save JeffreyVdb/2de36692a9d53ddf476028fc83a8dede to your computer and use it in GitHub Desktop.
Save JeffreyVdb/2de36692a9d53ddf476028fc83a8dede to your computer and use it in GitHub Desktop.
Count terraform workspace managed resources
#!/bin/bash
set -euo pipefail
count_managed_resources() {
jq '[.resources[] | select(.mode == "managed") | select(.type == "terraform_data" or .type == "null_resource" | not) | .instances | flatten[]] | length'
}
ROOT_DIR=${1:-.}
ABS_ROOT_DIR=$(readlink -f "$ROOT_DIR")
total_workspaces=0
total_managed_resources=0
while read -r backend_file; do
dir=$(dirname "$backend_file")
initial_workspace=$(terraform -chdir="$dir" workspace show)
workspaces=$(terraform -chdir="$dir" workspace list | perl -pe 's/^\*?\s+//g')
for workspace in $workspaces; do
terraform -chdir="$dir" workspace select "$workspace" >/dev/null
managed_resources=$(terraform -chdir="$dir" state pull | count_managed_resources)
total_managed_resources=$((total_managed_resources + managed_resources))
total_workspaces=$((total_workspaces + 1))
echo "Amount of managed resources in workspace $workspace: $managed_resources"
done
if [[ $(terraform -chdir="$dir" workspace show) != "$initial_workspace" ]]; then
terraform -chdir="$dir" workspace select "$initial_workspace" >/dev/null
fi
done < <(find "$ABS_ROOT_DIR" -type f -name "backend.tf")
echo
echo "Total number of managed resources: $total_managed_resources"
echo "Total number of workspaces: $total_workspaces"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment