-
-
Save mi-wood/0c53a13e4b7a2c78e2a9 to your computer and use it in GitHub Desktop.
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
require 'aws-sdk-core' | |
require 'yaml' | |
# class for updating vpc route53 | |
class OptimizelyDNS | |
def initialize(options = {}) | |
@region = options['region'] ||= 'us-east-1' | |
@domain = options['domain'] ||= 'default-domain' | |
@vpc_id = options['vpc-id'] ||= 'vpc-xxxxxxxx' | |
@zones = options['zones'] | |
@zones ||= { 'A' => 'ZXXXXXXXXXXX', 'PTR' => 'ZXXXXXXXXXXXX', 'CNAME' => 'ZXXXXXXXXXXXX' } | |
@route53 = Aws::Route53::Client.new(region: @region) | |
end | |
def create_record(name, value, record_type) | |
puts "Record for #{name} to #{value} of type #{record_type}" | |
@route53.change_resource_record_sets( | |
hosted_zone_id: @zones[record_type], | |
change_batch: { | |
changes: [ | |
{ | |
action: 'UPSERT', | |
resource_record_set: { | |
name: name.strip, | |
type: record_type, | |
ttl: 60, | |
resource_records: [{ value: value.strip }], | |
}, | |
}, | |
], | |
}, | |
) | |
end | |
# rubocop:disable MethodLength | |
def populate_tags | |
Aws.config[:ec2] = { region: @region } | |
ec2 = Aws::EC2::Client.new | |
filters = [{ name: 'vpc-id', values: [@vpc_id] }] | |
resp = ec2.describe_instances(filters: filters) | |
resp.reservations.each do |reservation| | |
reservation.instances.each do |instance| | |
ip = instance.private_ip_address | |
raw_name = instance.tags.select { |tag| tag['key'] == 'Name' }.first | |
name = raw_name['value'] unless raw_name.nil? | |
name ||= '' | |
raw_aliases = instance.tags.select { |tag| tag['key'] == 'aliases' }.first | |
aliases = raw_aliases['value'].split(',') unless raw_aliases.nil? | |
aliases ||= [] | |
next if name.empty? | |
fqdn = get_fqdn(name) | |
create_record(fqdn, ip, 'A') | |
create_record("#{ip.split('.').reverse.join('.')}.in-addr.arpa", fqdn, 'PTR') | |
next if aliases.empty? | |
aliases.each do |ali| | |
create_record(get_fqdn(ali), fqdn, 'CNAME') | |
end | |
end | |
end | |
end | |
# just reads a yaml file which is an array of key: value | |
def populate_overrides | |
overrides = YAML.load_file('overrides.yml') | |
overrides.each do |name, ip| | |
fqdn = get_fqdn(name) | |
create_record(fqdn, ip, 'A') | |
create_record("#{ip.split('.').reverse.join('.')}.in-addr.arpa", fqdn, 'PTR') | |
end | |
end | |
private | |
def get_fqdn(name) | |
"#{name}.#{@region}.#{@domain}" | |
end | |
end | |
if __FILE__ == $PROGRAM_NAME | |
dns = OptimizelyDNS.new | |
dns.populate_tags | |
dns.populate_overrides | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment