Dive into Digital Ocean

Pragmatic way of HTTP API usage

Philip Sahli

Introduction

Why you must read this

A co-worker of mine told me about DigitalOcean some weeks ago. DigitalOcean is providing cloud server instances.
In this tutorial I write about my attempts to create a instance. On DigitalOcean instances are called droplets.
DigitalOcean provides an API which enables us to do every step with curl cli command. The API responds with data in JSON format and the commands loads the id's of the created objects in a environment variable in your shell to make them available for the next step.

Signup

Get your account

Visit https://www.digitalocean.com/?refcode=4a74aa6905d4 and signup for an account. Note your "Client ID" and create a "API Key". Take note that the api key will displayed only once.

When you are done store your CLIENT_ID and your API_KEY in environment variables for later use.

export CLIENT_ID=YOUR_CLIENT_ID
export API_KEY=YOUR_API_KEY

We also store the URL for the API in a variable to shorten the commands a little bit.

export API_URL="https://api.digitalocean.com"

Keys

Setup keypair

Create on your workstation a ssh keypair:
 
ssh-keygen -t dsa
Enquote the public key and save it in the PUB_KEY environment variable.
PUB_KEY=`cat $HOME/.ssh/id_dsa.pub|python -c"import sys;import urllib;print urllib.quote(sys.stdin.readlines()[0])"`
Upload the key with the name "testserver".

Droplet

Create the box

DROPLET_ID=`curl -s "$API_URL/droplets/new/?client_id=$CLIENT_ID&api_key=$API_KEY&name=testvm&size_id=66&image_id=12573&region_id=2 &ssh_key_ids=$SSH_KEY_ID"|\ python -c"import sys,json; print json.loads(sys.stdin.readlines()[0])['droplet']['id']"` && echo $DROPLET_ID 

Repeat the following command until the droplet is created (status is active) and the ouput includes an ip address:
IP_ADDR=`curl -s "$API_URL/droplets/$DROPLET_ID?client_id=$CLIENT_ID&api_key=$API_KEY"|\ python -c"import sys,json; print json.loads(sys.stdin.readlines()[0])['droplet']['ip_address']"` && echo $IP_ADDR 

Use the box

Now you can log into the server with 'root', the server is reachable on the ip address from the previous command:
 

ssh root@$IP_ADDR

Destroy the box


At the end of this example you can destroy the droplet with following command:
 

curl -s "$API_URL/droplets/$DROPLET_ID/destroy/?client_id=$CLIENT_ID&api_key=$API_KEY"|python -mjson.tool