Skip to content

Instantly share code, notes, and snippets.

@Craftworks
Created July 17, 2010 07:54
Show Gist options
  • Save Craftworks/479339 to your computer and use it in GitHub Desktop.
Save Craftworks/479339 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use File::Temp 'tempfile';
require 5.008;
my $hosts = '/etc/hosts';
my ($new, $tempfile) = tempfile('UNLINK' => 1);
my $new_content = join '', <DATA>, instances();
print $new $new_content;
close $new;
chmod 0644, $tempfile;
open my $old, '<', $hosts or die $!;
my $old_content = join '', <$old>;
close $old;
if ( $new_content ne $old_content ) {
rename $tempfile, $hosts or die $!;
open my $bak, '>', "$hosts.bak" or die $!;
print $bak $old_content;
close $bak;
}
sub instances {
my %host;
open my $fh, '-|', 'ec2-describe-instances' or die "Failed to exec\n";
my @instances = grep /^INSTANCE/, <$fh>;
close $fh or die($? ? "Command failed" : $!);
unless ( @instances ) {
die "no instances\n";
}
for ( @instances ) {
my $hostname = (split /\t/)[3];
my $address = sprintf '%u.%u.%u.%u', unpack 'C*', (gethostbyname $hostname)[4];
$host{ get_hostname($address) } = $address;
}
my $lines = '';
for my $hostname ( sort keys %host ) {
$lines .= sprintf "%s\t%s\n", $host{$hostname}, $hostname;
}
return $lines;
}
sub get_hostname {
my $address = shift;
open my $fh, '-|', 'ssh', $address, 'hostname', '-s' or die $!;
my $hostname = <$fh>;
close $fh or die($? ? "Command failed" : $!);
unless ( $hostname ) {
die "Failed: $address\n";
}
return $hostname;
}
__DATA__
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
127.0.0.1 localhost.localdomain localhost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment