Last active
June 7, 2023 09:43
-
-
Save JeffreyVdb/2de36692a9d53ddf476028fc83a8dede to your computer and use it in GitHub Desktop.
Count terraform workspace managed resources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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