|
- import ovh
-
-
- # OVH API specific code
- client = ovh.Client()
- regions = ['GRA7', 'SBG5', 'DE1', 'UK1', 'BHS5']
-
- def get_base_url():
- service = client.get('/cloud/project')[0]
- return f"/cloud/project/{service}"
-
- base_url = get_base_url()
-
- # User management
- # users are actually named ssh_keys
- def get_users():
- ssh_keys = client.get(base_url + '/sshkey')
- return [
- [
- k['id'],
- k['name'].split('_')[1],
- k['publicKey'],
- ]
- for k in ssh_keys
- if k['name'].startswith('ssh_')
- ]
-
- def add_user(user, key):
- res = client.post(base_url + '/sshkey',
- name = 'ssh_' + user,
- publicKey = key
- )
- return res
-
- def delete_user(user_id):
- res = client.delete(base_url + '/sshkey/' + user_id)
- return res
-
-
- # Instance management
- # Server model for a region
- def get_flavor_id(region, name='s1-2'):
- flavors = client.get(base_url + '/flavor')
- flavorId = [f['id'] for f in flavors if f['name']
- == name and f['region'] == region][0]
- return flavorId
-
- # OS image for a region
- def get_image_id(region, name='Ubuntu 20.04'):
- images = client.get(base_url + '/image')
- imageId = [i['id'] for i in images if i['name']
- == name and i['region'] == region][0]
- return imageId
-
- def get_instances():
- ovh_instances = client.get(base_url + '/instance')
- instances = []
- for i in ovh_instances:
- id_inst = i['id']
- name = i['name']
- if not name.startswith('eica-'):
- continue
- if i['ipAddresses']:
- ip = i['ipAddresses'][0]['ip']
- else:
- ip = 'Waiting...'
- region = i['region']
- status = i['status']
- instances.append([id_inst, name, ip, region, status])
- return instances
-
- def create_instance(eleve_id, name, region):
- image_id = get_image_id(region)
- flavor_id = get_flavor_id(region)
- client.post(base_url + '/instance',
- name='eica-' + name,
- sshKeyId=eleve_id,
- flavorId=flavor_id,
- imageId=image_id,
- region=region
- )
-
- def delete_instance(instance_id):
- print(base_url + '/instance/' + instance_id)
- client.delete(base_url + '/instance/' + instance_id)
|