An IPython notebook that I use to create a digitalocean.com droplet to host a minecraft server. I've currently hardcoded a reference to the Ansible Playbook, which I've posted at https://gist.github.com/rdhyee/66f1aa40b6ea520c9e6e. There's code to use the Ansible Python API to play the playbook -- though clearly I can use the command line to do so. I've also been using the digitalocean Python module to launch a droplet. Ansible has facilities to launch droplets, but I've not used those capabilities yet.

https://github.com/koalalorenzo/python-digitalocean

To install:

 pip install -U python-digitalocean
In [ ]:
import digitalocean
from digitalocean_key import CLIENT_ID, API_KEY

manager = digitalocean.Manager(client_id=CLIENT_ID, api_key=API_KEY)

global_images = dict([(image.name, image) for image in manager.get_global_images()])
all_regions = dict([(region.name, region) for region in manager.get_all_regions()])
all_sizes = dict([(size.name, size) for size in manager.get_all_sizes()])
all_ssh_keys = dict([(key.name, key) for key in manager.get_all_sshkeys()])


def make_standard_droplet(name, size='512MB'):
    droplet = digitalocean.Droplet(client_id=CLIENT_ID,
                               api_key=API_KEY,
                               name = name,
                               region_id=all_regions['San Francisco 1'].id, #San Francisco 1
                               image_id=global_images['Ubuntu 12.04.3 x64'].id, #Ubuntu 12.04.3 x64 Server
                               size_id=all_sizes[size].id, #512MB
                               backup_active=False)

    droplet.create(ssh_key_ids=all_ssh_keys['RY laptop'].id)
    
In [ ]:
[(size_label, size.id) for (size_label, size) in all_sizes.iteritems()]
In [ ]:
global_images
In [ ]:
# create a droplet

droplets_to_create = ['minecraft1']

for name in droplets_to_create:
    make_standard_droplet(name)
In [ ]:
import digitalocean
from digitalocean_key import CLIENT_ID, API_KEY

manager = digitalocean.Manager(client_id=CLIENT_ID, api_key=API_KEY)

droplets = manager.get_all_droplets()
[(droplet.id, droplet.name, droplet.ip_address) for droplet in droplets]

instance = droplets[0]
In [ ]:
# copy a command to ssh into the instance

cmdstring = "ssh -oStrictHostKeyChecking=no [email protected]{0}".format(instance.ip_address)
# works on a mac
! echo "$cmdstring" | pbcopy
cmdstring
In [ ]:
from ansible.playbook import PlayBook
from ansible import callbacks
from ansible import utils

import jinja2
from tempfile import NamedTemporaryFile
import os

# this example fills in mandatory params: playbook, callbacks, runner_callbacks, stats 
# drawing inspiration from https://github.com/ansible/ansible/blob/release1.3.3/bin/ansible-playbook#L138

playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
stats = callbacks.AggregateStats()
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)

# let's dynamically generate the host_list

HOST_LIST_TEMPLATE = """
[local]
localhost

[{{group_name}}]
{{ip_address}}
"""

template = jinja2.Template(HOST_LIST_TEMPLATE)

from tempfile import NamedTemporaryFile

temp = NamedTemporaryFile(delete=False)
temp.write(template.render({'group_name':'minecraft_do', 'ip_address':instance.ip_address}))
temp.close()

playbook = PlayBook(remote_user='root',
                    playbook='/Users/raymondyee/D/Document/Working_with_Open_Data/working-open-data/notebooks/minecraft.yml',
                    callbacks=playbook_cb,
                    runner_callbacks=runner_cb,
                    stats=stats,
                    host_list=temp.name
                    )

results = playbook.run()

# clean up
os.remove(temp.name)

results
In [ ]:
# run this cell if you want to destroy droplet

for droplet in droplets:
    droplet.destroy()

Using dynamic inventory and command line invocation

In [ ]:
import digitalocean
from digitalocean_key import CLIENT_ID, API_KEY

manager = digitalocean.Manager(client_id=CLIENT_ID, api_key=API_KEY)

global_images = dict([(image.name, image) for image in manager.get_global_images()])
all_regions = dict([(region.name, region) for region in manager.get_all_regions()])
all_sizes = dict([(size.name, size) for size in manager.get_all_sizes()])
all_ssh_keys = dict([(key.name, key) for key in manager.get_all_sshkeys()])


PLAYBOOK_PATH = '/Users/raymondyee/D/Document/Working_with_Open_Data/working-open-data/notebooks/minecraft_do.yml'

EXTRA_VARS = {'ansible_client_id':CLIENT_ID,
              'ansible_api_key': API_KEY,
              'ssh_key_id': all_ssh_keys['RY laptop'].id,
              'image_id':global_images['Ubuntu 12.04 x64'].id,
              'region_id': all_regions['San Francisco 1'].id,
              'size_id': all_sizes['512MB'].id,
              'java_memory': '512M'
              }

extra_vars = " ".join(["{0}={1}".format(k,v) for (k,v) in EXTRA_VARS.items()])

!ansible-playbook  --verbose -u root --extra-vars "$extra_vars" $PLAYBOOK_PATH
In [ ]:
ansible_command = 'ansible-playbook --verbose -u root --extra-vars "{0}" {1}'.format(extra_vars, PLAYBOOK_PATH)
! echo '$ansible_command' | pbcopy
ansible_command
In [ ]:
try:
    import dopy
    from dopy.manager import DoError, DoManager
except ImportError as e:
    print "failed=True msg='dopy >= 0.2.2 required for this module'"
    sys.exit(1)

if dopy.__version__ < '0.2.2':
    print "failed=True msg='dopy >= 0.2.2 required for this module'"
    sys.exit(1)
In [ ]:
import dopy
from dopy.manager import DoError, DoManager

dopy.__version__
In [ ]: