Skip to content

Instantly share code, notes, and snippets.

@ibrezm1
Created July 29, 2024 21:25
Show Gist options
  • Save ibrezm1/f2ff903af62501278a85a41905762658 to your computer and use it in GitHub Desktop.
Save ibrezm1/f2ff903af62501278a85a41905762658 to your computer and use it in GitHub Desktop.
Get all service account keys in multiple projects
#!/bin/bash
# Get the current date and the date 9 months ago
current_date=$(date +%Y-%m-%d)
nine_months_ago=$(date -d "$current_date - 9 months" +%Y-%m-%d)
# Get the list of all projects
projects=("zeta-yen-319702")
# Temporary file to store all keys
tmpfile=$(mktemp)
# Iterate through each project
for project in $projects; do
echo "Checking project: $project"
# Get the list of service accounts in the project
service_accounts=$(gcloud iam service-accounts list --project "$project" --format="value(email)")
# Iterate through each service account
for sa in $service_accounts; do
echo "Checking service account: $sa"
# Get the keys for the service account and append to the temporary file
gcloud iam service-accounts keys list --iam-account="$sa" --project="$project" --format="json" >> "$tmpfile"
done
done
# Print the keys in a table sorted by validAfterTime
cat "$tmpfile" | jq -s '.[] | sort_by(.validAfterTime) | .[] | {name: .name, validAfterTime: .validAfterTime}' | jq -r '[.name, .validAfterTime] | @tsv' | column -t
# Remove the temporary file
rm "$tmpfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment