Skip to content

Instantly share code, notes, and snippets.

@linyows
Last active December 17, 2015 13:38
Show Gist options
  • Save linyows/5618117 to your computer and use it in GitHub Desktop.
Save linyows/5618117 to your computer and use it in GitHub Desktop.
Generate the Hosts Dynamically on AWS
#!/usr/bin/env ruby
# README
#
# Generate the Hosts Dynamically
# ==============================
#
# Usage
# -----
#
# add to `/etc/cron.d/aws`:
#
# ```sh
# SHELL=/bin/bash
# PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin
# MAILTO=root
# AWS_ACCESSKEY=?????
# AWS_SECRETKEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#
# @reboot /var/batches/generate_hosts.rb yourdomain.com yourdomain.lan
# */5 * * * * /var/batches/generate_hosts.rb yourdomain.com yourdomain.lan
# ```
#
# Author
# ------
#
# - [linyows](https://github.com/linyows)
#
# License
# -------
#
# MIT
require 'aws-sdk'
access_key = ENV['AWS_ACCESSKEY']
secret_key = ENV['AWS_SECRETKEY']
if access_key.nil? || access_key.empty? || secret_key.nil? || secret_key.empty?
puts "Empty AWS_ACCESSKEY or AWS_SECRETKEY"
exit 0
end
if ARGV.size < 2
puts "Usage: #{$0} <domain> <internal_domain> <aws_region_url> <dry-run>"
exit 0
end
domain = ARGV[0]
internal_domain = ARGV[1]
aws_region = ARGV[2] || 'ec2.us-east-1.amazonaws.com'
dryrun = ARGV[3] || false
hosts_path = '/etc/hosts'
hosts = ''
pattern = <<-RUBY
# dynamically generated hosts
# see cron & #{__FILE__}
.*
# end
RUBY
AWS.config(access_key_id: access_key,
secret_access_key: secret_key,
ec2_endpoint: aws_region)
ec2 = AWS::EC2.new
ec2.instances.each do |i|
next unless i.status.eql? :running
name = i.tags[:Name].strip
hosts << <<-"RUBY".gsub(/^\s+/, '')
#{i.private_ip_address}\t\t#{name}.#{internal_domain}\t#{name}
#{i.ip_address}\t\t#{name}.#{domain}
RUBY
end
hosts = pattern.gsub('.*', hosts.strip)
current_hosts = File.read(hosts_path)
new_hosts = current_hosts =~ /#{pattern}/m ?
current_hosts.gsub(/(#{pattern})/m, hosts) : current_hosts + hosts
dryrun ? puts(new_hosts) : File.write(hosts_path, new_hosts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment