Skip to content

Instantly share code, notes, and snippets.

@suzumura-ss
Last active December 18, 2015 03:59
Show Gist options
  • Save suzumura-ss/5722256 to your computer and use it in GitHub Desktop.
Save suzumura-ss/5722256 to your computer and use it in GitHub Desktop.
Regist public-hostname to Route53.
#!/usr/local/bin/ruby
require 'aws-sdk'
require 'yaml'
# Get informations of the instance.
instance_id = `curl -s http://169.254.169.254/latest/meta-data/instance-id`
endpoint = ['ec2', `curl -s http://169.254.169.254/latest/meta-data/public-hostname`.split('.')[1], 'amazonaws.com'].join('.')
ip = `curl -s http://169.254.169.254/latest/meta-data/public-ipv4`
CONFIG = YAML.load_file(File.expand_path("/etc/"+File.basename(__FILE__)+".conf"))
AWS.config(:access_key_id=>CONFIG["access_key"], :secret_access_key=>CONFIG["secret_key"])
# Gets the public-hostname to register Route53.
ec2 = AWS::EC2.new(:ec2_endpoint=>endpoint)
host_name = ec2.instances[instance_id].tags["hostName"] || CONFIG["host_name"] || ARGV[0]
p( {:instance_id=>instance_id, :endpoint=>endpoint, :ip=>ip, :host_name=>host_name} )
if host_name.nil? or host_name.empty?
puts "EC2-tag `hostName` is empty."
exit 1
end
# Regist to Route53.
e = AWS::Route53::HostedZone.new(CONFIG["zone_id"]).rrsets.map{|r| (r.name==host_name+".")? r: nil}.find{|r| r}
batch = AWS::Route53::ChangeBatch.new(CONFIG["zone_id"])
batch << AWS::Route53::DeleteRequest.new(e.name, e.type, :ttl=>e.ttl, :resource_records=>e.resource_records) if e
batch << AWS::Route53::CreateRequest.new(host_name, "A", :ttl=>300, :resource_records=>[{:value=>ip}])
batch.call
# Regist to os.
host, domain = host_name.split(/\./, 2)
system("hostname #{host}") if host
system("domainname #{domain}") if domain
access_key: "YOUR ACCESS KEY"
secret_key: "YOUR SECRET KEY"
zone_id: "YOUR ZONE ID"
# host_name: "public host name."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment