Skip to content

Instantly share code, notes, and snippets.

@hernandesbsousa
Last active August 29, 2015 14:08
Show Gist options
  • Save hernandesbsousa/73cc99fc0cad72c19b9a to your computer and use it in GitHub Desktop.
Save hernandesbsousa/73cc99fc0cad72c19b9a to your computer and use it in GitHub Desktop.
Route Table Assigner for AWS Nat instances
#!/bin/env python
# This script should run at boot (set as user data) on NAT instances
# - Disables the source/dest check for the current instance
# - Modifies default route for the specified route table to the instance running this
import argparse
import boto
import boto.utils
import os
import sys
dry_run = False
def set_up():
parser = argparse.ArgumentParser()
parser.add_argument("route_table_id", help="VPC route table id you want to modify")
parser.parse_args()
# Authentication via iam role
vpc_conn = boto.connect_vpc()
ec2_conn = boto.connect_ec2()
try:
instance_id = boto.utils.get_instance_metadata()['instance-id']
instance_region = boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]
except:
fail("Could not get EC2 instance metadata!")
def disable_src_dest_check():
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)
def config_route_table():
print "Modifying route table {0}".format(route_table_id)
try:
vpc_conn.replace_route(route_table_id, '0.0.0.0/0', instance_id=instance_id, dry_run=dry_run)
except Exception, e:
fail("Issue setting route table [{0}]: {1}".format(route_table_id, e))
print "Gateway set!"
def fail(error_msg="An unexpected error occurred"):
print error_msg
sys.exit(1)
set_up()
disable_src_dest_check()
config_route_table()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment