Skip to content

Instantly share code, notes, and snippets.

@svdgraaf
Last active March 22, 2017 11:00
Show Gist options
  • Save svdgraaf/894d0ca96eb67577d824f65db7fe5e77 to your computer and use it in GitHub Desktop.
Save svdgraaf/894d0ca96eb67577d824f65db7fe5e77 to your computer and use it in GitHub Desktop.
Update AWS instance hosts file with all internal dns names for VPC members. Useful when dns discovery is not useable/available.
#!/usr/bin/env python
import boto3
import requests
ec2 = boto3.resource('ec2')
# fetch the instance id
response = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
instance_id = response.text
# fetch the vpc_id
current_instance = ec2.Instance(instance_id)
vpc_id = current_instance.vpc_id
# loop through all instances, and get their details
hosts = []
for i in ec2.instances.all():
if i.vpc_id != vpc_id:
continue
# append both the full hostname, as well as the short hostname
hosts.append("%s %s\n" % (i.private_ip_address, i.private_dns_name))
hosts.append("%s %s\n" % (i.private_ip_address, i.private_dns_name.split('.')[0]))
# open the current hosts file, read the first 3 lines, and append the new hosts
with open('/etc/hosts', 'r') as f:
lines = f.readlines()
start = lines[0:3]
new_lines = start + hosts
new_contents = "".join(new_lines)
with open('/etc/hosts', 'w') as f:
print new_contents
f.write(new_contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment