Digital Ocean API Wrapper

DateReadtime 3 minutes Tags

I found myself wanting to take snapshots of my digital ocean droplets. I wrote a quick python script that wraps the api and allows me to snapshot my droplet on a regular basis.

#! /usr/bin/env python

import requests
import time

API_KEY=''
CLI_ID=''

def fetch(path, opts={}):
    opts['api_key'] = API_KEY
    opts['client_id'] = CLI_ID
    opts = '&'.join(["%s=%s" % (key, opts[key]) for key in opts.keys()])
    return requests.get("https://api.digitalocean.com/%(path)s/?%(opts)s" % locals()).json()

def show(droplet_id):
    return fetch("droplets/%s" % droplet_id)

def shutdown(droplet_id):
    return fetch("droplets/%s/shutdown" % droplet_id)

def power_off(droplet_id):
    return fetch("droplets/%s/power_off" % droplet_id)

def power_on(droplet_id):
    return fetch("droplets/%s/power_on" % droplet_id)

def snapshot(droplet_id, name):
    return fetch("droplets/%s/snapshot" % droplet_id, {u'name': name})

def event(event_id):
    return fetch("events/%s" % event_id)

def reboot(droplet_id):
    return fetch("droplets/%s/reboot" % droplet_id)

def wait(event_id):
    e = event(event_id)
    if e["status"] == "OK":
        if e["event"]["action_status"] == 'done':
            return "event_id: %s" % event_id
        else:
            if e["event"]["percentage"] != '3':
                print "Percentage: %s%%" % e["event"]["percentage"]
            else:
                print ".",
            time.sleep(1)
            wait(event_id)


def take_snapshot(droplet_id, droplet_name):
    start = time.time()
    print "Shutting down droplet"
    s = shutdown(droplet_id)
    if s['status'] == "OK":
        event_id = s['event_id']
        print wait(event_id)
    else:
        return s['status']

    print "Taking snapshot"
    name = "Backup of %%s at %s" % time.strftime("%Y-%m-%d %H:%M")
    s = snapshot(droplet_id, name % droplet_name)
    if s['status'] == "OK":
        event_id = s['event_id']
        print wait(event_id)
    else:
        return s['status']

    print "Powering back on"
    s = power_on(droplet_id)
    if s['status'] == "OK":
        event_id = s['event_id']
        print wait(event_id)
    else:
        return s['status']

    return str(time.time() - start)

def power_on_droplet(droplet_id):
    start = time.time()
    s = power_on(droplet_id)
    if s['status'] == "OK":
        event_id = s['event_id']
        print wait(event_id)
    else:
        return s['status']

    return str(time.time() - start)



if __name__ == '__main__':
    #print fetch('droplets')
    droplets = [(droplet[u'id'], droplet[u'name']) for droplet in fetch('droplets')[u'droplets']]

    for droplet_id, droplet_name in droplets:
        #print droplet_id, show(droplet_id)
        #print power_on_droplet(droplet_id)
        print take_snapshot(droplet_id, droplet_name)