Skip to content

Instantly share code, notes, and snippets.

@gtato
Last active November 6, 2015 19:33
Show Gist options
  • Save gtato/38841ab753bd43094380 to your computer and use it in GitHub Desktop.
Save gtato/38841ab753bd43094380 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import libcloud.security, 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,
ex_force_auth_url=keystone_url,
ex_force_auth_version='2.0_password',
ex_tenant_name=tenant)
def get_by_id_or_name(key, id_or_name, rlist):
by_id = filter(lambda x: x.id==id_or_name, rlist)
if len(by_id) > 0:
return by_id[0]
by_name = filter(lambda x: x.name==id_or_name, 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,
'networks':[network]
}
instance = driver.create_node(**kwargs)
fip = get_floating_ip()
nr_attempts = 0
while (nr_attempts < 5):
try:
driver.ex_attach_floating_ip_to_node(instance, fip.ip_address)
break
except BaseHTTPError:
print 'Attempt %s: probably failed because the VM is not yet associated to a network' % (nr_attempts+1)
time.sleep(1)
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