+#!/usr/bin/python
+
+import boto.utils
+import boto.ec2
+import boto.vpc
+import sys
+
+dry_run = False
+
+# AWS access/secret keys
+aws_access = None
+aws_secret = None
+
+# Get all of the instance info e.g. curl 169.254.169.254/latest/meta-data/
+try:
+ instance_info = boto.utils.get_instance_metadata()
+except:
+ print "Could not get EC2 instance ID!"
+ sys.exit(1)
+
+instance_id = instance_info['instance-id']
+region_name = instance_info['placement']['availability-zone'][:-1]
+vpc_id = instance_info['network']['interfaces']['macs'][instance_info['mac']]['vpc-id']
+
+vpc_conn = boto.vpc.connect_to_region(region_name, aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
+ec2_conn = boto.ec2.connect_to_region(region_name, aws_access_key_id=aws_access, aws_secret_access_key=aws_secret)
+
+# Turn off Source/Destination checking if it's on
+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)
+
+# Get the managed route tables for my VPC
+rt = vpc_conn.get_all_route_tables(filters={'vpc_id':vpc_id,'tag:managed':'yes'})
+
+# Just in case there's more than one
+for table in rt:
+ # See if there's a default route (0.0.0.0/0)
+ gw_route = next((route for route in table.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" % (table.id, gw_route.destination_cidr_block, instance_id)
+ try:
+ # If there is delete it, because I'm taking it over
+ vpc_conn.delete_route(table.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:
+ # Make me the default route, I'm the router now!
+ vpc_conn.create_route(table.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)
+
+