Skip to content

Instantly share code, notes, and snippets.

@micahbf
Last active April 6, 2016 17:42
Show Gist options
  • Save micahbf/dcd90bf72ca99ffa64c0 to your computer and use it in GitHub Desktop.
Save micahbf/dcd90bf72ca99ffa64c0 to your computer and use it in GitHub Desktop.
#!/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
@micahbf
Copy link
Author

micahbf commented Dec 31, 2015

requires gem aws-sdk ~> 2

I recommend creating a IAM user that only has permission route53:ChangeResourceRecordSets

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment