Last active
December 12, 2017 02:19
-
-
Save lestrrat/2407c11947fbe2cd3c8770c959aa06d3 to your computer and use it in GitHub Desktop.
Delete dangling TCP Load Balancers on GCP Created By Kubernetes Services
This file contains 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
use strict; | |
use JSON (); | |
my $src = qx(gcloud compute forwarding-rules list --format json); | |
my $json = JSON->new; | |
my $rules = $json->decode( $src ); | |
for my $rule (@$rules) { | |
print "forwarding-rule $rule->{name}:\n"; | |
if ($rule->{description} =~ m{kubernetes\.io/service-name}) { # TCP (k8s Service with external address) | |
my ($target_pool) = ($rule->{target} =~ m{/([^/]+)$}); | |
my ($region) = ($rule->{region} =~ m{/([^/]+)$}); | |
my $target_src = qx(gcloud compute target-pools describe $target_pool --region $region --format json); | |
my $target = $json->decode( $target_src ); | |
my $exists = 0; | |
print " + checking target pool $target_pool:\n"; | |
for my $instance_url (@{$target->{instances}}) { | |
my ($instance_zone, $instance_name) = ($instance_url =~ m{/zones/([^/]+)/.+/([^/]+)$}); | |
my $instance_src = qx(gcloud compute instances describe $instance_name --zone $instance_zone --format json 2>/dev/null); | |
if (!$instance_src) { | |
print " - $instance_name not found\n"; | |
} else { | |
$exists++; | |
} | |
} | |
print " + target pool $target_pool ", ($exists > 0 ? "OK" : "is dangling"), "\n"; | |
if ($exists == 0) { | |
print " + DELETING forwarding-rule/target-pool $rule->{name}\n"; | |
local $ENV{CLOUDSDK_CORE_DISABLE_PROMPTS} = 1; | |
system("gcloud compute forwarding-rules delete $rule->{name} --region $region"); | |
system("gcloud compute target-pools delete $target_pool --region $region"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment