Created
May 3, 2016 23:57
-
-
Save pypt/0b1f896f8612a92284ff3f7d8c642b36 to your computer and use it in GitHub Desktop.
Return stale EC2 instance count
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
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use v5.18; | |
use Paws; | |
use Date::Parse; | |
use Data::Dumper; | |
sub stale_instance_count($) | |
{ | |
my $stale_instance_threshold = shift; | |
my $stale_instance_count = 0; | |
my $regions = Paws->service( 'EC2', region => 'us-east-1' )->DescribeRegions; | |
foreach my $region ( @{ $regions->Regions } ) { | |
my $region_name = $region->RegionName; | |
say STDERR "Testing region $region_name..."; | |
my $ec2 = Paws->service( 'EC2', region => $region_name ); | |
my $instances = $ec2->DescribeInstances; | |
for my $reservation ( @{ $instances->Reservations } ) { | |
for my $instance ( @{ $reservation->Instances } ) { | |
my $launch_time = $instance->LaunchTime; | |
my $launch_timestamp = str2time( $launch_time ); | |
unless ( defined $launch_timestamp ) { | |
die "Unable to parse LaunchTime '$launch_time'."; | |
} | |
if ( time() - $stale_instance_threshold > $launch_timestamp ) { | |
my $instance_id = $instance->InstanceId; | |
say "Stale instance $instance_id on region $region_name"; | |
++$stale_instance_count; | |
} | |
} | |
} | |
} | |
return $stale_instance_count; | |
} | |
sub main() | |
{ | |
# Read by Paws; set those in /etc/munin/plugin-conf.d/mediacloud.conf | |
# (https://github.com/berkmancenter/mediacloud-munin/blob/master/etc/munin/plugin-conf.d/mediacloud.conf.example) | |
$ENV{ AWS_ACCESS_KEY_ID } = '...'; | |
$ENV{ AWS_SECRET_ACCESS_KEY } = '...'; | |
# Seconds to allow the instance to be running | |
my $stale_instance_threshold = 60 * 60 * 24; | |
say "Stale instance count: " . stale_instance_count( $stale_instance_threshold ); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment