Create droplet with python

We use DigitalOcean for ssd cloud server. It has a very simple and clear website to use, but sometimes it does not enough a wide range of synchronous processes. At that dark point, DigitalOcean API flashed like the sun. By this way, we implemented some python scripts to manage our servers. A simple create droplet python script is below.


import sys
import datetime
import requests
import json

def create_droplets(number_of_droplets):
    now = datetime.datetime.now()
    now = now.strftime("%Y%m%d-%H%M")
    for i in xrange(number_of_droplets):
        i = i+1
        droplet_name = now + "-droplet-" + str(i)

It’s very clear, first of all we generate current time oriented name of droplets,


        url = "https://api.digitalocean.com/droplets/new?
               client_id=[this_is_your_client_id]
               &api_key=[yes_this_is_your_api_key]
               &name=" + droplet_name + "
               &size_id=[your_size_id]
               &image_id=[your_image_id]
               &region_id=[your_region_id]
               &ssh_key_ids=[your_ssh_key_ids]"

secondly populate the API request url with proper parameters,


        result = requests.get(url)
        result_json = json.loads(result.text)
        status = result_json['status']

thirdly use get method of requests and response convert to json format


        if status == 'OK':
            droplet = result_json['droplet']
            print ("droplet name='%s' and id=%s is created"
                   %(droplet['name'],droplet['id']))
        else:
            print ("HTTP GET status code is %s" 
                   %result.status_code")
            print result_json['error_message']

finally get droplet or print error


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "usage is like : 
               python create_droplet.py droplet_count"
    else:
        number_of_droplets = int(sys.argv[1])
        droplets = create_droplets(number_of_droplets)

ordinary main function shows usage of the script file.