前提: Route53 にベースとなるドメインが設定されていること
require "aws-sdk"
AWS.config access_key_id: ENV["AWS_ACCESS_KEY_ID"],
secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]
def modify_route53 subdomain, operation, opt = {ttl: 300}
resp = AWS::Route53.new.client.list_hosted_zones
resp[:hosted_zones].each do |zone|
if zone[:name] == "#{ENV['BASE_DOMAIN']}."
elb_name = ENV["AWS_ELB_DNS_NAME"]
dns_name = "#{subdomain}.#{zone[:name]}"
record_type = "CNAME"
options = {
ttl: opt[:ttl],
resource_records: [{value: elb_name}]
}
request_params = [dns_name, record_type, options]
rrsets = AWS::Route53::HostedZone.new(zone[:id]).rrsets
batch = AWS::Route53::ChangeBatch.new zone[:id]
case operation
when :create
next if rrsets[dns_name, record_type].exists?
batch << AWS::Route53::CreateRequest.new(*request_params)
when :delete
next unless rrsets[dns_name, record_type].exists?
batch << AWS::Route53::DeleteRequest.new(*request_params)
else
raise "Error: Unknown operation."
end
batch.call
break
end
end
end
def register_to_route53 subdomain
modify_route53 subdomain, :create
end
def unregister_from_route53 subdomain
modify_route53 subdomain, :delete
end
#### test.sh ##########################
# #!/bin/sh
# AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID \
# AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY \
# BASE_DOMAIN=YOUR_BASE_DOMAIN \
# AWS_ELB_DNS_NAME=YOUR_ELB_DNS_NAME \
# ruby -e "require '/path/to/route53.rb'; register_to_route53 'foo'"