add vpcaccess role
[awsible] / roles / vpcaccess / files / routeUpdater.py
1 #!/usr/bin/python
2
3 import boto.utils
4 import boto.ec2
5 import boto.vpc
6 import sys
7
8 dry_run = False
9
10 # AWS access/secret keys
11 aws_access = None
12 aws_secret = None
13
14 # Get all of the instance info e.g. curl 169.254.169.254/latest/meta-data/
15 try:
16 instance_info = boto.utils.get_instance_metadata()
17 except:
18 print "Could not get EC2 instance ID!"
19 sys.exit(1)
20
21 instance_id = instance_info['instance-id']
22 region_name = instance_info['placement']['availability-zone'][:-1]
23 vpc_id = instance_info['network']['interfaces']['macs'][instance_info['mac']]['vpc-id']
24
25 vpc_conn = boto.vpc.connect_to_region(region_name, aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
26 ec2_conn = boto.ec2.connect_to_region(region_name, aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
27
28 # Turn off Source/Destination checking if it's on
29 source_dest_check = ec2_conn.get_instance_attribute(instance_id, 'sourceDestCheck')['sourceDestCheck']
30 print "Source/Dest check: %s" % (source_dest_check,)
31
32 if source_dest_check:
33 print "Instance must have source/dest checking disabled to NAT properly!"
34 try:
35 ec2_conn.modify_instance_attribute(instance_id, 'sourceDestCheck', False, dry_run=dry_run)
36 except Exception, e:
37 print "Could not modify source/dest check: %s" % (e,)
38 sys.exit(1)
39
40 # Get the managed route tables for my VPC
41 rt = vpc_conn.get_all_route_tables(filters={'vpc_id':vpc_id,'tag:managed':'yes'})
42
43 # Just in case there's more than one
44 for table in rt:
45 # See if there's a default route (0.0.0.0/0)
46 gw_route = next((route for route in table.routes if route.destination_cidr_block == '0.0.0.0/0'), None)
47 if not gw_route:
48 print "Could not find default gw route in routing table!"
49 else:
50 print "Found a gateway route: %s, %s, %s" % (table.id, gw_route.destination_cidr_block, instance_id)
51 try:
52 # If there is delete it, because I'm taking it over
53 vpc_conn.delete_route(table.id, '0.0.0.0/0', dry_run=dry_run)
54 except Exception, e:
55 print "Could not delete gw route! %s" % (e,)
56 sys.exit(1)
57 try:
58 # Make me the default route, I'm the router now!
59 vpc_conn.create_route(table.id, '0.0.0.0/0', instance_id=instance_id, dry_run=dry_run)
60 except Exception, e:
61 print "Could not replace gw route! %s" % (e,)
62 sys.exit(1)
63
64