aboutsummaryrefslogblamecommitdiff
path: root/python/reinstall_cloud_instance.py
blob: c488fda23f4de2d3e408f14a476a492e46821bc8 (plain) (tree)
























































                                                                                                 
# -*- encoding: utf-8 -*-
import json
try:
    from ovh import ovh
except ImportError:
    # In case it's installed globally
    import ovh
import sys

# Credentials are stored in ~/.ovh.conf
# See ovh/README.rst
client = ovh.Client()

projects_list = client.get('/cloud/project/')
if len(projects_list) > 1:
    print("More than one project is not supported, taking the first one")
project = projects_list[0]
instances_list = client.get('/cloud/project/{}/instance'.format(project))
instances = dict(map(lambda x: (x["id"], x), instances_list))
if sys.argv[-1] in instances:
    instance = instances[sys.argv[-1]]
else:
    print("Instance not in list:")
    for instance in instances_list:
        print("{}: {}".format(instance["name"], instance["id"]))
    sys.exit(1)

current_image = instance["imageId"]
available_images = client.get('/cloud/project/{}/image'.format(project),
        osType="linux",
        region=instance["region"])
available_images_ids = list(map(lambda x: x["id"], available_images))

def print_images(available_images):
    for image in available_images:
        print("{}: {}".format(image["name"], image["id"]))

def reinstall(image_id):
    return client.post('/cloud/project/{}/instance/{}/reinstall'.format(project, instance["id"]),
        imageId=image_id)

if "--get-state" in sys.argv:
    print(instance["status"])
elif "--use-current" in sys.argv:
    if current_image in available_images_ids:
        print("Current image still available, using it")
        print(reinstall(current_image))
    else:
        print("Current image no more available. Chose among:")
        print_images(available_images)
elif sys.argv[-1] in available_templates:
    print("Chosen image available, using it")
    print(reinstall(current_image))
else:
    print("Chosen image not available. Chose among:")
    print_images(available_images)