-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathec2masq.py
43 lines (34 loc) · 1.53 KB
/
ec2masq.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/python
import boto3
import socket
# You have to supply this value or come up with a clever way to figure it out at runtime.
# It's the IP of your local VPC's DNS server - usually your VPC network address "+2".
LOCAL_DNS="10.0.0.2"
ec2 = boto3.resource('ec2')
config_template = '''# Auto generated by ec2masq.py
except-interface=lo
listen-address=%(localip)s
bind-interfaces
no-resolv
log-queries
# White-listed domains we have to allow to make certain things like EMR work
# We'll just forward these queries to the locally-enabled VPC DNS server
# You can add more stuff here if you have another DNS server in your infrastructure you trust
server=/s3.amazonaws.com/%(localdns)s
server=/kms.amazonaws.com/%(localdns)s
server=/kms.us-east-1.amazonaws.com/%(localdns)s
server=/repo.us-east-1.amazonaws.com/%(localdns)s
# And here are all the programatically added entries
'''
local_ip = socket.gethostbyname(socket.gethostname())
config = config_template % {"localip": local_ip, "localdns": LOCAL_DNS})
# Get all the running instances in your account
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
# Make some records and add to the config
for instance in instances:
reverse_ip = '.'.join(instance.private_ip_address.split('.')[::-1])
record = 'address=/%s/%s\n' % (instance.private_dns_name, instance.private_ip_address)
record += 'ptr-record=%s.in-addr.arpa,%s' % (reverse_ip, instance.private_dns_name)
config += '%s\n' % record
# Printing is still cool, right?
print config