Last week I was toying with IBM Cloud tranzient servers, and got to setting a webhook url to be notified if the server needs to be reclaimed.

In case the name doesn’t tells you anything, Transient Virtual Servers is the IBM Cloud equivalent to AWS Spot Instances.

Creating a tranzient servers is easy enough trhough IBM Cloud portal, setting the webhook URL is not. It’s available only through API here

In order to use SoftLayer, we need to generate a key.

But, before that, what are the SoftLayer API ? The SoftLayer API powers many of the features in the IBM Cloud console.

Generate API Key

In order to login to SoftLayer API we need an user and a Key.

For IBM Cloud, the user is LITTERALLY apikey. The API Key can be generated using the this url https://cloud.ibm.com/iam/apikeys .

Next, create a file ~/.softlayer for Linux or ~/AppData/Roaming/softlayer/.softlayer for Windows with the next content:

[softlayer]
# For IBMCloud ApiKeys
# https://sldn.softlayer.com/article/authenticating-softlayer-api/#cloud-api
username = apikey
api_key = 32CharacterLongKey

endpoint_url = https://api.softlayer.com/rest/v3.1

# Set to a number to stop waiting after that many seconds
timeout = 0

# If you need to proxy requests through something
# proxy = 'http://somehost'

Logging in SoftLayer

Now, it Python land, install SoftLayer using pip:

pip install SoftLayer

Next, let’s try to login to SoftLayer and get the account information:

import SoftLayer
# This is nice for printing out results from the API as raw JSON
from pprint import pprint as pp 

client = SoftLayer.create_client_from_env()

result = client.call('SoftLayer_Account', 'getObject')
pp(result)

If everthing it’s ok, on running the python file, the IBM Cloud account information will be displayed.

Getting VM List and Setting WebHook URL

In order to list the VM’s from IBM Cloud account we use the VSManager.list_instances() API.

For example:

    def listVMs(self, public_ip):
        mgr = SoftLayer.VSManager(self.client)
        for vsi in mgr.list_instances(public_ip=public_ip):
            print(f"Id: {vsi['id']} and fullyQualifiedDomainName: {vsi['fullyQualifiedDomainName']}")
            return vsi

In order to set the Webhook URL we’ll use Set Webhook API, something like this:

    def setWebHook(self, vm_id, url, secret):
        result = self.client.call('SoftLayer_Virtual_Guest', 'setTransientWebhook', url, secret, id=vm_id)
        pp(result)