Skip to content

Instantly share code, notes, and snippets.

@btotharye
Created September 3, 2019 10:52
Show Gist options
  • Save btotharye/99918dbfff4a548299c68d40cb75a074 to your computer and use it in GitHub Desktop.
Save btotharye/99918dbfff4a548299c68d40cb75a074 to your computer and use it in GitHub Desktop.
Atlas Mongo VPC Peering with AWS
import os
import requests
from requests.auth import HTTPDigestAuth
import pprint
import json
import boto3
import time
def mongo_peer_setup(
vpc_id,
vpc_cidr,
group_id,
aws_region,
aws_account):
base_url = "https://cloud.mongodb.com/api/atlas/v1.0"
peerurl = base_url + "/groups/" + group_id + "/peers"
containerurl = base_url + "/groups/" + group_id + "/containers"
containers=requests.get(
containerurl,
auth=HTTPDigestAuth(
os.environ["ATLAS_USER"],
os.environ["ATLAS_USER_KEY"]
)
)
# Ensure we have a Peer Network Container
try:
container_results = containers.json()['results']
except:
raise Exception(containers.json()['errorCode'])
# Now we should have Peer Container Object
if container_results:
mongo_cidr = container_results[0]['atlasCidrBlock']
mongo_container_id = container_results[0]['id']
peer_data = {
"accepterRegionName" : aws_region,
"awsAccountId" : aws_account,
"containerId" : mongo_container_id,
"providerName" : "AWS",
"routeTableCidrBlock" : vpc_cidr,
"vpcId" : vpc_id
}
# Send Request to API for Peering
headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
mongo_peering=requests.post(
peerurl,
auth=HTTPDigestAuth(
os.environ["ATLAS_USER"],
os.environ["ATLAS_USER_KEY"]
),
headers=headers,
data=json.dumps(peer_data)
)
peer_results = mongo_peering.json()
# Check Peer Results
try:
if peer_results['statusName'] == 'INITIATING':
print("Peer Status initiated, now accepting on AWS side")
time.sleep(7)
# Now Looking Up VPC Peer on AWS Side
client = boto3.client('ec2')
peer_response = client.describe_vpc_peering_connections(
Filters=[
{
'Name': 'accepter-vpc-info.vpc-id',
'Values': [
vpc_id,
]
},
{
'Name': 'status-code',
'Values': [
'pending-acceptance'
]
}
]
)
# Should only have 1 pending so grab first result
vpc_peer_id = peer_response['VpcPeeringConnections'][0]['VpcPeeringConnectionId']
vpc_accept_response = client.accept_vpc_peering_connection(
VpcPeeringConnectionId=vpc_peer_id
)
print(vpc_accept_response['VpcPeeringConnection']['Status'])
print("Waiting for peer link to become active just a minute...")
time.sleep(5)
peer_update = client.describe_vpc_peering_connections(
Filters=[
{
'Name': 'vpc-peering-connection-id',
'Values': [
vpc_peer_id,
]
}
]
)
if peer_update['VpcPeeringConnections'][0]['Status']['Code'] == 'active':
print("Peer successfully activated: {}".format(peer_update))
else:
print("Ran into a issue, here is peer update response: {}".format(peer_update))
except:
# See if Peer Already Exists, Exit with except if so
if peer_results['errorCode'] == 'PEER_ALREADY_EXISTS':
raise Exception(peer_results['errorCode'])
mongo_peer_setup(
vpc_id='vpc-xxx',
vpc_cidr='10.116.0.0/16',
group_id="xxx",
aws_region='us-east-1',
aws_account='xxx'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment