Need API to execute a Catalog to provision VM

Is there a way to execute a Catalog automatically (or via API method) scheduled at specific time to test if the provision of servers are fine. We would need this to test this as a workflow testing after building new template every month. Could you please guide us with any API method or let us know if this needs to be raised a new feature request.

This can be automated using the Morpheus API. The general flow of how this would work is detailed below:

  • Order the desired catalog item use the name of the catalog item along with the required options/inputs.
  • Fetch the ordered catalog item to identify the ID of the associated instance(s).
  • Poll the status of the instance(s) until it returns a finalized state of either success or failure.

API Endpoints
The following list of API endpoints can be used to automate the catalog ordering process.

Below is an example python script for reference purposes:

import json
from time import sleep
import requests
import urllib3
import sys
import os

urllib3.disable_warnings()

def fetch_token(url, username, password):
    # Define Oauth API Endpoint URL
    tokenurl = f"{url}/oauth/token"
    # Add Query Parameters
    querypayload = {}
    querypayload['grant_type'] = 'password'
    querypayload['scope'] = 'write'
    querypayload['client_id'] = 'morph-api'
    # Add Headers
    headers = {}
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    headers['accept'] = 'application/json'
    # Add Authentication Payload
    payload = {'username': username, 'password': password}
    # Post Oauth Request To Fetch API TOken
    response = requests.post(tokenurl, headers=headers, data=payload, verify=False, params=querypayload)
    tokenjson = response.json()
    return tokenjson

def get_catalog_item(url, token, id):
    headers = {
      'Authorization': f"BEARER {token}",
    }
    mopho_url = f"{url}/api/catalog/items/{id}"
    response = requests.get(mopho_url, headers=headers, verify=False,)
    return response.json()

def order_catalog_item(url, token, name):
    headers = {
      'Authorization': f"BEARER {token}",
    }

    jsonPayload = {}
    jsonPayload["order"] = {}
    jsonPayload["order"]["items"] = []

    catalogItem = {}
    catalogItem["type"] = {}
    catalogItem["type"]["name"] = name

    catalogItem["config"] = {}

    jsonPayload["order"]["items"].append(catalogItem)
    
    requestPayload = json.dumps(jsonPayload)
    mopho_url = f"{url}/api/catalog/orders"
    response = requests.post(mopho_url, headers=headers, verify=False, data=requestPayload)
    responsePayload = response.json()
    print("==== INITIAL ORDER RESPONSE ====")
    print(responsePayload)
    items = []
    for item in responsePayload["order"]["items"]:
        items.append(item["id"])
    return items[0]

def get_instance(url, token, id):
    headers = {
      'Authorization': f"BEARER {token}",
    }
    mopho_url = f"{url}/api/instances/{id}"
    response = requests.get(mopho_url, headers=headers, verify=False,)
    return response.json()

def poll_order_status(url, token, order):
    status = "provisioning"

    while status == "provisioning" or status == "pending":
        itemdetails = get_catalog_item(url, token, int(order))
        print("==== ORDER DETAILS POLLING RESPONSE ====")
        print(itemdetails)
        itemType = itemdetails["item"]["refType"]
        if itemType == "Instance":
            status = itemdetails["item"]["instance"]["status"]
        print("current status: " + status )
        sleep(30)

    return status, itemType

def process_instance(payload):
    instance = payload["item"]["instance"]
    return instance["id"]

def main():
    url = 'https://test.grt.local'
    tokenPayload = fetch_token(url, "admin", "password123")
    token = tokenPayload['access_token']

    # Order a catalog item named "apidemo"
    item = order_catalog_item(url, token, "apidemo")
    print("==== INITIAL ORDER FIRST ITEM RESPONSE ====")
    print(item)

    # Wait for the catalog item details to populate
    sleep(15)

    # Fetch catalog item details
    itemdetails = get_catalog_item(url, token, item)
    print("==== ORDER DETAILS RESPONSE ====")
    print(itemdetails)

    # Poll the catalog item status
    status, itemType = poll_order_status(url, token, item)
    if status == "failed":
        sys.exit(1)

    if itemType == "Instance":
        id = process_instance(itemdetails)
        instance_details = get_instance(url, token, id)
        print("==== ORDER SUCCESSFUL RESPONSE ====")
        print(instance_details["instance"]["containerDetails"][0]["ip"])
        print(instance_details["instance"]["containerDetails"][0]["externalHostname"])

if __name__ == "__main__":
    main()
2 Likes