Created
January 27, 2016 16:59
-
-
Save Ashex/5191cbf9aa2effd8d487 to your computer and use it in GitHub Desktop.
Add Peering connection to AWS Route Tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__author__ = 'ahmed' | |
import boto3, botocore | |
import argparse | |
def get_vpcid(sitename, client): | |
response = client.describe_vpcs( | |
Filters = [{ | |
'Name': 'tag:Site', | |
'Values': [ | |
sitename | |
] | |
} | |
] | |
) | |
if len(response['Vpcs']) == 1: | |
return response['Vpcs'][0]['VpcId'] | |
else: | |
raise ValueError('More than one VPC returned!') | |
def get_route_tables(vpcid, resource): | |
vpc = resource.Vpc(vpcid) | |
route_tables = list(vpc.route_tables.all()) | |
return map(lambda route: route.id, route_tables) | |
def add_peering_route(route_table_id, cidr, peeringid, resource): | |
route_table = resource.RouteTable(route_table_id) | |
response = route_table.create_route(DestinationCidrBlock=cidr, | |
VpcPeeringConnectionId=peeringid) | |
return response | |
def main(): | |
argparser = argparse.ArgumentParser() | |
argparser.add_argument('--site', help='Name of the Site VPC', required=True) | |
argparser.add_argument('--cidr', help='CIDR to add route for', required=True) | |
argparser.add_argument('--peeringid', help='Peering connection we are going to use', required=True) | |
argparser.add_argument('--profile', help='AWS Profile to use', required=True) | |
args = argparser.parse_args() | |
cidr = args.cidr | |
site = args.site | |
peeringid = args.peeringid | |
profile = args.profile | |
if profile != None: boto3.setup_default_session(profile_name=profile) | |
ec2resource = boto3.resource('ec2', region_name='eu-central-1') | |
ec2Client = boto3.client('ec2', region_name='eu-central-1') | |
vpcid = get_vpcid(site, client = ec2Client) | |
print('Looking up route tables for %s' % vpcid) | |
route_tables = get_route_tables(vpcid, ec2resource) | |
print ('Retrieved %s tables, proceeding to add tables' % len(route_tables)) | |
for table_id in route_tables: | |
print('Adding route for %s to %s' % (cidr, peeringid)) | |
try: | |
response = add_peering_route(table_id, cidr, peeringid, ec2resource) | |
if response: | |
continue | |
else: | |
print('Error occurred adding route to %s' % table_id) | |
except botocore.exceptions.ClientError as e: | |
if e.response['Error']['Code'] == 'RouteAlreadyExists': | |
print('Route already exists on %s, continuing' % table_id) | |
continue | |
else: | |
print('Unexpected error: %s' % e) | |
print('Routes have been added!') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment