Created
April 15, 2022 21:14
-
-
Save clickfreak/65f29b58bb0fb255e798a6087a65cb28 to your computer and use it in GitHub Desktop.
How to find regions with instances in G-Core Labs cloud
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
#!/usr/bin/env python3 | |
import os | |
import json | |
import requests | |
import logging | |
# you can create permanent token in account settings: https://accounts.gcorelabs.com/profile/api-tokens | |
APIKEY = '<your_permanent_token>' | |
LOGLEVEL = os.environ.get('LOGLEVEL', 'WARNING').upper() | |
log_format = u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s' | |
logging.basicConfig(level=LOGLEVEL, | |
format=log_format) | |
class GCORELABS_API(): | |
def __init__(self, api_url='https://api.gcorelabs.com', api_key=None): | |
# TODO: set it via program arg param | |
self.API_URL = api_url | |
if api_key is None: | |
raise Exception("The API key is required") | |
self.session = self.config_session(api_key) | |
@staticmethod | |
def config_session(api_key): | |
s = requests.Session() | |
s.headers = { | |
'Content-Type': 'application/json; charset=utf-8', | |
'Authorization': 'APIKey {}'.format(api_key) | |
} | |
return s | |
def do_request(self, method, path, data=None, **kwargs): | |
if path[0] != '/': | |
path = '/' + path | |
full_url = self.API_URL + path | |
r = self.session.request(method, | |
full_url, | |
data=data, | |
**kwargs) | |
if r.status_code not in [404]: | |
return r.json() | |
else: | |
return None | |
def main(): | |
api = GCORELABS_API('https://api.gcorelabs.com/cloud/v1', api_key=APIKEY) | |
# https://api.cloud.gcorelabs.com/v1/regions | |
regions = api.do_request('get', '/regions') | |
regions_list = regions.get('results', []) | |
# https://api.cloud.gcorelabs.com/v1/projects | |
projects = api.do_request('get', '/projects') | |
projects_list = projects.get('results', []) | |
for project in projects_list: | |
print("Walk through project {} (id={})".format(project['name'], project['id'])) | |
for region in regions_list: | |
url_params = { | |
'project_id': project['id'], | |
'region_id': region['id'] | |
} | |
# https://api.cloud.gcorelabs.com/v1/instances/{project_id}/{region_id} | |
instances_result = api.do_request('get', | |
'instances/{project_id}/{region_id}'.format(**url_params)) | |
if instances_result is not None: | |
instances_list = instances_result.get('results', []) | |
if len(instances_list): | |
print("found {} instances in project {}, region {}:".format(instances_result['count'],project['name'], region['display_name'])) | |
print(json.dumps(instances_result, indent=2)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment