Created
June 14, 2011 19:35
-
-
Save dialtone/1025673 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
#!/usr/bin/env python | |
import os | |
import shutil | |
import socket | |
from optparse import OptionParser | |
from boto import ec2 | |
BASE = """ | |
127.0.0.1 localhost %s | |
# The following lines are desirable for IPv6 capable hosts | |
::1 ip6-localhost ip6-loopback | |
fe00::0 ip6-localnet | |
ff00::0 ip6-mcastprefix | |
ff02::1 ip6-allnodes | |
ff02::2 ip6-allrouters | |
ff02::3 ip6-allhosts | |
""" | |
def main(options, hostname): | |
if not (options.aws_secret_key and options.aws_access_key): | |
return | |
os.environ['AWS_ACCESS_KEY_ID'] = options.aws_access_key | |
os.environ['AWS_SECRET_ACCESS_KEY'] = options.aws_secret_key | |
conn = ec2.connect_to_region(region_name="us-west-1") | |
all_tags = conn.get_all_tags(filters={"tag:dns": "*"}) | |
new_lines = [BASE % hostname] | |
for tag in all_tags: | |
instance = conn.get_all_instances([tag.res_id])[0].instances[0] | |
for dns_name in tag.value.strip().split(","): | |
if instance.state == "running": | |
new_lines.append( | |
"%s %s.internal %s" % ( | |
socket.gethostbyname(instance.public_dns_name), | |
dns_name, | |
dns_name) | |
) | |
f = open('/etc/hosts.new', 'wb') | |
f.write("\n".join(new_lines)) | |
f.write("\n") | |
f.flush() | |
f.close() | |
shutil.move('/etc/hosts.new', '/etc/hosts') | |
if __name__ == '__main__': | |
""" | |
e.g, update_hosts.py --secret=<SECRET_KEY> --api=<API_KEY> | |
""" | |
usage = "usage: %prog [options]" | |
parser = OptionParser(usage=usage) | |
parser.add_option("--secret", action="store", dest="aws_secret_key", | |
default=os.environ.get('AWS_SECRET_ACCESS_KEY'), help="AWS Secret Access Key") | |
parser.add_option("--api", action="store", dest="aws_access_key", | |
default=os.environ.get('AWS_ACCESS_KEY_ID'), help="AWS Access Key") | |
(options, args) = parser.parse_args() | |
if len(args) != 1: | |
raise Exception("Must know who we are in order to work") | |
main(options, args[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment