Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
import, time
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.exceptions import BaseHTTPError
uname = 'dummy'
pwd = 'foo'
tenant = 'dummy'
keystone_url = 'http://hostip:5000'
size_id = 'flavor_name_or_id' # 'm1.small'
img_id = 'image_name_or_id'
network_id = 'network_name_or_id'
instance_name = 'my-libcloud-server'
sec_group = 'dummy-secgroup'
key_name = 'dummy-keypair'
Driver = get_driver(Provider.OPENSTACK)
driver = Driver(uname, pwd, secure=False,
def get_by_id_or_name(key, id_or_name, rlist):
by_id = filter(lambda x:, rlist)
if len(by_id) > 0:
return by_id[0]
by_name = filter(lambda x:, rlist)
if len(by_name) > 0:
return by_name[0]
raise ValueError('%s is not a valid value for %s' % (id_or_name, key))
size = get_by_id_or_name('size', size_id, driver.list_sizes())
img = get_by_id_or_name('image', img_id, driver.list_images())
network = get_by_id_or_name('network', network_id, driver.ex_list_networks())
#you could filter this as well if you had more than one floating ip pool
pool = driver.ex_list_floating_ip_pools()[0]
def get_floating_ip():
free_fips = filter(lambda x: x.node_id==None, driver.ex_list_floating_ips())
return free_fips[0] if len(free_fips) > 0 else pool.create_floating_ip()
kwargs = {
'size': size,
'image': img,
'name': instance_name,
'ex_securitygroup': sec_group,
'ex_keyname': key_name,
instance = driver.create_node(**kwargs)
fip = get_floating_ip()
nr_attempts = 0
while (nr_attempts < 5):
driver.ex_attach_floating_ip_to_node(instance, fip.ip_address)
except BaseHTTPError:
print 'Attempt %s: probably failed because the VM is not yet associated to a network' % (nr_attempts+1)
if nr_attempts == 0:
raise Exception('Unable to assing a floating IP to the VM!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment