Last active
April 6, 2016 17:42
-
-
Save micahbf/dcd90bf72ca99ffa64c0 to your computer and use it in GitHub Desktop.
Quick Route53 DynDNS script. Ruby translation of https://willwarren.com/2014/07/03/roll-dynamic-dns-service-using-amazon-route53/
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 ruby | |
require 'time' | |
require 'logger' | |
require 'aws-sdk' | |
AWS_REGION = "us-east-1" | |
AWS_KEY_ID = "" | |
AWS_SECRET_KEY = "" | |
HOSTED_ZONE_ID = "" | |
RESOURCE_NAME = "blah.example.com." | |
LAST_IP_FILE = "./.dyndns_last_ip" | |
LOG_FILE = "/var/log/dyndns.log" | |
LOG_LEVEL = Logger::WARN | |
log_file_path = File.expand_path(LOG_FILE, File.dirname(__FILE__)) | |
begin | |
logger = Logger.new(log_file_path) | |
logger.level = LOG_LEVEL | |
rescue Errno::ENOENT | |
File.open(log_file_path, "w").close | |
retry | |
end | |
begin | |
path = File.expand_path(LAST_IP_FILE, File.dirname(__FILE__)) | |
last_ip = File.read(path).chomp | |
rescue Errno::ENOENT | |
logger.warn "last ip file not found: #{path}" | |
last_ip = nil | |
end | |
current_ip = `dig +short myip.opendns.com @resolver1.opendns.com`.chomp | |
unless $? == 0 | |
logger.fatal "dig exited with error code: #{$?}" | |
logger.close | |
exit 1 | |
end | |
unless current_ip =~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ | |
logger.fatal "invalid ip: '#{current_ip}'" | |
logger.close | |
exit 2 | |
end | |
if last_ip == current_ip | |
logger.info "ip hasn't changed from #{last_ip}, exiting" | |
logger.close | |
exit | |
end | |
route53 = Aws::Route53::Client.new( | |
region: AWS_REGION, | |
access_key_id: AWS_KEY_ID, | |
secret_access_key: AWS_SECRET_KEY | |
) | |
begin | |
route53.change_resource_record_sets({ | |
hosted_zone_id: HOSTED_ZONE_ID, | |
change_batch: { | |
comment: "dyndns script change at #{Time.now.iso8601}", | |
changes: [ | |
{ | |
action: "UPSERT", | |
resource_record_set: { | |
name: RESOURCE_NAME, | |
type: "A", | |
ttl: 60, | |
resource_records: [ | |
{ | |
value: current_ip, | |
}, | |
], | |
}, | |
}, | |
], | |
}, | |
}) | |
rescue Aws::Errors::ServiceError => e | |
logger.fatal "aws failed with error: #{e.class}: #{e.message}" | |
logger.close | |
exit 3 | |
end | |
File.write(path, current_ip) | |
logger.info "changed ip from #{last_ip} to #{current_ip}" | |
logger.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires gem
aws-sdk ~> 2
I recommend creating a IAM user that only has permission
route53:ChangeResourceRecordSets