7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby] Route53 で ELBにサブドメインを振る

Last updated at Posted at 2014-07-30

前提: 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'"
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?