voodoojello
12/31/2014 - 10:32 PM

A *really* basic AWS Route 53 Dynamic DNS Updater in Perl

A really basic AWS Route 53 Dynamic DNS Updater in Perl

#!/usr/bin/perl
#
# AWS Route 53 Dynamic DNS Updater
# (c)2014 Mark Page [m.e.page@gmail.com]
# Wed Dec 31 08:35:56 CST 2014
#
use strict;
use warnings;
use LWP::Simple qw(!head);
use WebService::Amazon::Route53;

my $app_home   = '/opt/aws-tools';
my @domains    = ('some.tld.','someother.tld.','yetanother.tld.',); # note the trailing dots!
my $outside_ip = get_outside_ip();

if ($outside_ip->{'error'}) { die $outside_ip->{'error'}; }

if ($outside_ip->{'info'}) {
    print $outside_ip->{'info'};
    if ($outside_ip->{'info'} =~ m/unchanged/i) { exit 0; }
    }

my $r53 = WebService::Amazon::Route53->new (
    'id'  => '__YOUR_AWS_ID__', 
    'key' => '__YOUR_AWS_SECRET__',
    );

for my $d (0 .. (scalar(@domains) - 1)) {
    my $response = $r53->find_hosted_zone('name' => $domains[$d]);
    my $zone     = $response->{'hosted_zone'};
    my $result   = $r53->change_resource_record_sets(
        zone_id => $zone->{'id'},
        changes => [{
            action => 'upsert',
            name => $domains[$d], 
            type => 'A',
            ttl => 300,
            records => [$outside_ip->{'ip'},],
            }]
        );

    if ($result->{'status'}) { print localtime(time) . ': INFO: ' . $domains[$d] . ' [' . $result->{'status'} . ': ' . $result->{'id'} . "]\n"; }
    if ($r53->error->{'message'}) { print localtime(time) . ': ERROR: ' . $r53->error->{'message'} . "\n"; }
    }

exit;

sub get_outside_ip {
    my ($args) = @_;
    my ($_return);
    my $last_ip = '';

    if ($_return->{'ip'} = LWP::Simple::get("https://icanhazip.com/")) {
        $_return->{'ip'} =~ s/\n|\r//g;
        $_return->{'info'} .= localtime(time) . ': INFO: Got external IP: ' . $_return->{'ip'} . "\n";

        if (stat("$app_home/last_ip")) {
            open (my $in_cache,'<',"$app_home/last_ip"); $last_ip = join('',<$in_cache>); close ($in_cache);
            }
        }
    else {
        $_return->{'error'} = localtime(time) . ': ERROR: Could not get external IP!' . "\n";
        }
    
    if ($_return->{'ip'} eq $last_ip) {
        $_return->{'info'} .= localtime(time) . ': INFO: IP Address unchanged (' . $_return->{'ip'} . ')' . "\n";
        }
    
    open (my $out_cache,'>',"$app_home/last_ip"); print $out_cache $_return->{'ip'}; close ($out_cache);
    
    return $_return;
    }