forked from viyh/aws-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgateway-grabber.py
76 lines (61 loc) · 2.24 KB
/
gateway-grabber.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#
# Gateway Grabber - 2014-02-27
#
# Repoints the default gw for a routing table to the current instance
# that is running this script.
#
# Set the CFN_ROUTETABLE env var with your CloudFormation template
#
import boto
import boto.utils
import os
import sys
dry_run = False
# AWS access/secret keys (None if using EC2 role)
aws_access = None
aws_secret = None
region_name = 'us-east-1'
try:
cfn_routetable = os.environ['CFN_ROUTETABLE']
except:
print "CFN_ROUTETABLE environment variable is not set!"
sys.exit(1)
try:
instance_id = boto.utils.get_instance_metadata()['instance-id']
except:
print "Could not get EC2 instance ID!"
sys.exit(1)
vpc_conn = boto.connect_vpc(aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
ec2_conn = boto.connect_ec2(aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
try:
rt = vpc_conn.get_all_route_tables(route_table_ids=os.environ['CFN_ROUTETABLE'])[0]
except Exception, e:
print "Could not find route table [%s]: %s" % (os.environ['CFN_ROUTETABLE'], e)
sys.exit(1)
print "Found the route table: %s" % (rt.id,)
source_dest_check = ec2_conn.get_instance_attribute(instance_id, 'sourceDestCheck')['sourceDestCheck']
print "Source/Dest check: %s" % (source_dest_check,)
if source_dest_check:
print "Instance must have source/dest checking disabled to NAT properly!"
try:
ec2_conn.modify_instance_attribute(instance_id, 'sourceDestCheck', False, dry_run=dry_run)
except Exception, e:
print "Could not modify source/dest check: %s" % (e,)
sys.exit(1)
gw_route = next((route for route in rt.routes if route.destination_cidr_block == '0.0.0.0/0'), None)
if not gw_route:
print "Could not find default gw route in routing table!"
else:
print "Found a gateway route: %s, %s, %s" % (rt.id, gw_route.destination_cidr_block, instance_id)
try:
vpc_conn.delete_route(rt.id, '0.0.0.0/0', dry_run=dry_run)
except Exception, e:
print "Could not delete gw route! %s" % (e,)
sys.exit(1)
try:
vpc_conn.create_route(rt.id, '0.0.0.0/0', instance_id=instance_id, dry_run=dry_run)
except Exception, e:
print "Could not replace gw route! %s" % (e,)
sys.exit(1)
print "Gateway grabbed!"