Skip to content

Instantly share code, notes, and snippets.

@thbkrkr
Created February 27, 2020 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thbkrkr/57b2ddea122119bc7e0b6b789a94908c to your computer and use it in GitHub Desktop.
Save thbkrkr/57b2ddea122119bc7e0b6b789a94908c to your computer and use it in GitHub Desktop.
Remove orphaned forwarding-rules and target pools on Google Cloud
#!/bin/bash -eu
# Remove orphaned forwarding-rules and target pools on Google Cloud
list_target_pools() {
gcloud compute target-pools list --limit 1000 --format json | \
jq '.[] |
{
name: .name,
region: .region | split("/")[8],
instance: .instances[0] | split("/") |
{
zone: .[8],
name: .[10]
}
}' \
-c \
| sort > target-pools.json
}
list_instances() {
gcloud compute instances list --limit 1000 --format json | \
jq '.[] |
{
zone: .zone | split("/")[8],
name: .name
}' \
-c \
| sort > instances.json
}
clean_up() {
while read pool; do
if ! grep $(jq -c .instance <<< $pool) instances.json >/dev/null; then
name=$(jq -r .name <<< $pool)
region=$(jq -r .region <<< $pool)
echo $pool
gcloud compute forwarding-rules delete $name --region $region --quiet
gcloud compute target-pools delete $name --region $region --quiet
fi
done < <(jq . target-pools.json -c)
}
list_target_pools
list_instances
clean_up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment