Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Created August 14, 2024 00:48
Show Gist options
  • Save SafeEval/50b5343c632c884a23cb3fbe1d05258c to your computer and use it in GitHub Desktop.
Save SafeEval/50b5343c632c884a23cb3fbe1d05258c to your computer and use it in GitHub Desktop.
List out the VCS configs for all TFC workspaces in the organization
#!/bin/bash
# Script to pull details on all TFC workspaces and then focus on VCS configs.
# Note: jq is used to parse JSON, you need to install it if not already available
# Variables - Replace with your actual values
if [ -z $TFC_API_TOKEN ]; then
echo "Missing TFC_API_TOKEN environment variable";
exit 1;
fi
if [ -z $ORGANIZATION_NAME ]; then
echo "Missing ORGANIZATION_NAME environment variable";
exit 1;
fi
# API Endpoint
API_URL="https://app.terraform.io/api/v2/organizations/${ORGANIZATION_NAME}/workspaces"
# Initialize variables
page=1
per_page=100
combined_response=""
# Loop through all pages
while true; do
# Fetch the current page
response=$(curl -s \
--header "Authorization: Bearer $TFC_API_TOKEN" \
--header "Content-Type: application/vnd.api+json" \
"${API_URL}?page\[number\]=$page&page\[size\]=$per_page")
# Check if the API call was successful
if [ $? -ne 0 ]; then
echo "Failed to connect to Terraform Cloud API"
echo $response
exit 1
fi
# Append the current page's data to the combined response
if [ -z "$combined_response" ]; then
combined_response=$(echo "$response" | jq '.data')
else
combined_response=$(echo "$combined_response $(echo "$response" | jq '.data')" | jq -s 'add')
fi
# Check if there are more pages
next_page=$(echo "$response" | jq -r '.meta.pagination["next-page"]')
if [ "$next_page" == "null" ]; then
break
fi
# Move to the next page
page=$((page + 1))
done
# Output the combined JSON document
echo "$combined_response" | jq . > "workspace-list.json"
cat "workspace-list.json" \
| jq '.[] | {name: .attributes.name, "vcs-repo": .attributes."vcs-repo", "vcs-repo-identifier": .attributes."vcs-repo-identifier"}' \
> "workspace-vcs-configs.json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment