Wednesday, August 1, 2012

GCE part II - fun with the API


First make sure you use a git checkout, the api is a moving target:

git clone https://code.google.com/p/google-compute-engine-tools.gcelib/

Then simply:

#!/usr/bin/python

import logging
from gcelib import gce_util
from gcelib import gce_v1beta12
from gcelib import shortcuts

# Project-related configuration.
DEFAULT_PROJECT = 'PROJECT'  # Your project name goes here.
DEFAULT_ZONE = 'us-east1-a'
DEFAULT_IMAGE = 'projects/google/images/ubuntu-12-04-v20120621'
DEFAULT_MACHINE_TYPE = 'n1-standard-1'

# Change logging to INFO to see more or to DEBUG to see even more!
LOG_LEVEL = logging.ERROR

def main():
  # Performs the oauth2 dance.
  credentials = gce_util.get_credentials()
  defaults = gce_util.get_defaults()

  # Constructs an instance of GoogleComputeEngine.
  api = gce_v1beta12.GoogleComputeEngine(
      credentials,
      logging_level=LOG_LEVEL,
      default_project=defaults.project or DEFAULT_PROJECT,
      default_zone=defaults.zone or DEFAULT_ZONE,
      default_image=defaults.image or DEFAULT_IMAGE,
      default_machine_type=defaults.machine_type or DEFAULT_MACHINE_TYPE)

  # Creates 8 test instances synchronously.
  names = ['test-instance-{0}'.format(i) for i in xrange(8)]
  api.insert_instances(names, networkInterfaces=shortcuts.network())

  # Prints the names of all instances in the given project.
  for instance in api.all_instances():
    print instance.name
 
  api.wait_until_done()

if __name__ == '__main__':
  main()
          

Gets you up and running in seconds:

toofan:samples jcuff$ time ./go.py
test-instance-0
test-instance-1
test-instance-2
test-instance-3
test-instance-4
test-instance-5
test-instance-6
test-instance-7

real 0m10.847s
user 0m0.520s
sys 0m0.103s



yep, it really was that easy... 8 node cluster, 10 seconds.

jcuff% foreach h (0 1 2 3 4 5 6 7)
foreach? gcutil ssh test-instance-$h uname -a
foreach? end
Linux test-instance-0 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-1 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-2 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-3 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-4 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-5 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-6 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012
Linux test-instance-7 2.6.39-gcg-201203291735 #1 SMP Thu Mar 29 17:37:55 PDT 2012

Done


[any opinions here are all mine, and have absolutely nothing to do with my employer]
(c) 2011 James Cuff