Reputation: 21
Is there a way to automate AWS VPC Peering?
Upvotes: 1
Views: 175
Reputation: 21
Use the Lambda Python code below to configure your VPC ,should be Accepter VPC and then have an SNS trigger configured for this lambda and this select the best option for SNS allowed from the source. Rest the lambda will take care of what you will require in most of the manual work.
import boto3
client = boto3.client('ec2')
resource = boto3.resource('ec2')
vpc_peering_connection = client.describe_vpc_peering_connections(Filters=[{
'Name':'status-code',
'Values':['pending-acceptance','failed'] # Refer to BOTO3 documentation for filters of your choice
}])['VpcPeeringConnections']
route_tables = client.describe_route_tables()
def lambda_handler(event,context):
try:
list_of_vpcs_in_route_tables = []
for peering_con_vpc_info in vpc_peering_connection: # Gathering Peering VPC connection information
peering_id = peering_con_vpc_info['VpcPeeringConnectionId']
client.accept_vpc_peering_connection( VpcPeeringConnectionId = peering_id )
# for values in peering_con_vpc_info['RequesterVpcInfo']:
print('VPC Peering ID request accepted \t ' + peering_id) # Print PEERING CONNECTION ID
accpeter_vpc_id = peering_con_vpc_info['AccepterVpcInfo']['VpcId'] # Filtering ACCEPTERS VPID information
#Getting list of VPC found with ROUTE TABLES
for rt_tables_list in route_tables['RouteTables']: # Getting ALL THE ROUTE TABLES IN AN ACCOUNT
if accpeter_vpc_id in rt_tables_list['VpcId']: # Filtering with matching ACCEPTER VPCID with EXISTING ROUTE TABLE LIST OF VPCID's
print("===================================================================================================")
print("For the Accepter VPC\t" + accpeter_vpc_id +"\twith Routable ID\t" + rt_tables_list['RouteTableId'])
print("===================================================================================================")
DestinationBlock = peering_con_vpc_info['RequesterVpcInfo']['CidrBlock']
RoutablesID = rt_tables_list['RouteTableId']
VpcPeeringId = peering_con_vpc_info['VpcPeeringConnectionId']
client.create_route(DestinationCidrBlock = DestinationBlock,
RouteTableId = RoutablesID,
VpcPeeringConnectionId = VpcPeeringId)
print("Routes added successfully")
elif peering_con_vpc_info['Status']['Code'] == 'failed':
print('Peering has failed look for the exception errors')
except Exception as e:
print(e.args[-1])
Upvotes: 1