Last active
August 26, 2019 14:14
-
-
Save tfogo/5d02d31f8d337422f88e6c5482c6d224 to your computer and use it in GitHub Desktop.
Automate deploying with the mLab Management API
This file contains 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
################################################### | |
# Automate deploying with the mLab Management API # | |
# Link Here: # | |
################################################### | |
################# | |
# STEP 0: Setup # | |
################# | |
import os # for getting environment variables | |
import requests # for making HTTP requests | |
import json # for formatting JSON responses | |
from time import sleep # for sleeping between status requests | |
from pymongo import MongoClient # for querying the cluster | |
json_settings = { | |
'sort_keys': True, | |
'indent': 4 | |
} | |
BASE_URL = 'https://v1.api.mlab.com' | |
# Get your key headers from environment variables | |
headers = { | |
'access-key-id': os.getenv('MLAB_KEY_ID'), | |
'access-key-secret': os.getenv('MLAB_KEY_SECRET') | |
} | |
########################## | |
# STEP 1: Get Account ID # | |
########################## | |
# Send a request to /me | |
response = requests.get(f'{BASE_URL}/me', headers=headers) | |
response.raise_for_status() # Raise an error if not a 2XX status code | |
print("me Response:\n" + json.dumps(response.json(), **json_settings) + "\n") | |
# Get your account ID from the request | |
account_id = response.json()['account']['_id'] | |
print("Account ID:\n" + account_id + "\n") | |
############################ | |
# STEP 2: Create a Cluster # | |
############################ | |
json_data = { | |
'plan': 'aws-m1-std-cluster-v2', | |
'provider': 'aws', | |
'region': 'us-east-1', | |
'dbName': 'test-database', | |
'initialDbUser': { | |
'username': 'db_user', | |
'password': 'secure_pass' # Make sure to use a secure password | |
}, | |
'sslMode': 'deployment', | |
'name': 'new_deployment', | |
'environment': 'EnvironmentId' # Substitute your own environment ID | |
} | |
response = requests.post(f'{BASE_URL}/accounts/{account_id}/deployments', headers=headers, json=json_data) | |
response.raise_for_status() # Raise an error if not a 2XX status code | |
deployment = response.json() | |
deployment_id = deployment['_id'] | |
print("Provisioning request enqueued:\n" + json.dumps(deployment, **json_settings) + "\n") | |
connection_uri = deployment['connectionInfo']['uriTemplate'].format(**options.initialDbUser) | |
####################################### | |
# STEP 3: Check when cluster is built # | |
####################################### | |
status = '' | |
while status != 'OK': | |
sleep(10) | |
uri = f'{BASE_URL}/accounts/{account_id}/deployments/{deployment_id}/status' | |
response = requests.get(uri, headers=headers) | |
response.raise_for_status() # Raise an error if not a 2XX status code | |
status = response.json()['status'] | |
print("Status: " + status) | |
# If there's a problem building the cluster, throw an error. | |
if status == 'ERROR': | |
raise Exception("Error building cluster") | |
############################## | |
# STEP 4: Add firewall rules # | |
############################## | |
firewall_rules = { | |
'inboundAllowRules': [ | |
{ | |
'description': 'Open internet', | |
'ipAddressSpace': '0.0.0.0/0' | |
} | |
] | |
} | |
response = requests.put(f'{BASE_URL}/accounts/{account_id}/deployments/{deployment_id}/firewall', headers=headers, json=firewall_rules) | |
response.raise_for_status() # Raise an error if not a 2XX status code | |
print("Added firewall rule:\n" + json.dumps(response.json(), **json_settings) + "\n") | |
###################################### | |
# STEP 5: Query cluster with pymongo # | |
###################################### | |
client = MongoClient(connection_uri) | |
db = client[options['dbName']] | |
db['test_collection'].insert_one({'firstname': 'Ada', 'lastname': 'Lovelace'}) | |
print("Query result:\n" + db['test_collection'].find_one()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes thank you, I had a look at this API, but unfortunately I didn't see anything that suggest I could create a new deployment, aka new database via this new mongdb API , which is where I wanted to get to.