Compute Examples

Example: Creating a Node

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

RACKSPACE_USER = "your username"
RACKSPACE_KEY = "your key"

Driver = get_driver(Provider.RACKSPACE)
conn = Driver(RACKSPACE_USER, RACKSPACE_KEY)

# retrieve available images and sizes
images = conn.list_images()
# [<NodeImage: id=3, name=Gentoo 2008.0, driver=Rackspace  ...>, ...]
sizes = conn.list_sizes()
# [<NodeSize: id=1, name=256 server, ram=256 ... driver=Rackspace ...>, ...]

# create node with first image and first size
node = conn.create_node(name="test", image=images[0], size=sizes[0])
# <Node: uuid=..., name=test, state=3, public_ip=['1.1.1.1'],
#   provider=Rackspace ...>

Example: List Nodes Across Multiple Providers

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

EC2_ACCESS_ID = "your access id"
EC2_SECRET_KEY = "your secret key"
RACKSPACE_USER = "your username"
RACKSPACE_KEY = "your key"

EC2Driver = get_driver(Provider.EC2)
RackspaceDriver = get_driver(Provider.RACKSPACE)

drivers = [
    EC2Driver(EC2_ACCESS_ID, EC2_SECRET_KEY),
    RackspaceDriver(RACKSPACE_USER, RACKSPACE_KEY),
]

nodes = []
for driver in drivers:
    nodes += driver.list_nodes()
print(nodes)
# [ <Node: provider=Amazon, status=RUNNING, name=bob, ip=1.2.3.4.5>,
#   <Node: provider=Rackspace, status=REBOOT, name=korine, ip=6.7.8.9>, ... ]

# Reboot all nodes named 'test'
[node.reboot() for node in nodes if node.name == "test"]

Example: Bootstrapping Puppet on a Node

import os

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.compute.deployment import ScriptDeployment, SSHKeyDeployment, MultiStepDeployment

# Path to the public key you would like to install
KEY_PATH = os.path.expanduser("~/.ssh/id_rsa.pub")

# Shell script to run on the remote server
SCRIPT = """#!/usr/bin/env bash
apt-get -y update && apt-get -y install puppet
"""

RACKSPACE_USER = "your username"
RACKSPACE_KEY = "your key"

Driver = get_driver(Provider.RACKSPACE)
conn = Driver(RACKSPACE_USER, RACKSPACE_KEY)

with open(KEY_PATH) as fp:
    content = fp.read()

# Note: This key will be added to the authorized keys for the root user
# (/root/.ssh/authorized_keys)
step_1 = SSHKeyDeployment(content)

# A simple script to install puppet post boot, can be much more complicated.
step_2 = ScriptDeployment(SCRIPT)

msd = MultiStepDeployment([step_1, step_2])

images = conn.list_images()
sizes = conn.list_sizes()

# deploy_node takes the same base keyword arguments as create_node.
node = conn.deploy_node(name="test", image=images[0], size=sizes[0], deploy=msd)

Create an OpenStack node using trystack.org provider

trystack.org allows users to try out OpenStack for free. This example demonstrates how to launch an OpenStack node on the trystack.org provider using a generic OpenStack driver.

import libcloud.security
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# At the time this example was written, https://nova-api.trystack.org:5443
# was using a certificate issued by a Certificate Authority (CA) which is
# not included in the default Ubuntu certificates bundle (ca-certificates).
# Note: Code like this poses a security risk (MITM attack) and that's the
# reason why you should never use it for anything else besides testing. You
# have been warned.
libcloud.security.VERIFY_SSL_CERT = False

OpenStack = get_driver(Provider.OPENSTACK)

driver = OpenStack(
    "your username",
    "your password",
    ex_force_auth_url="https://nova-api.trystack.org:5443",
    ex_force_auth_version="2.0_password",
)

nodes = driver.list_nodes()

images = driver.list_images()
sizes = driver.list_sizes()
size = [s for s in sizes if s.ram == 512][0]
image = [i for i in images if i.name == "natty-server-cloudimg-amd64"][0]

node = driver.create_node(name="test node", image=image, size=size)

Create an OpenStack node using a local OpenStack provider

This example shows how to create a node using a local OpenStack installation. Don’t forget to replace your_auth_username, your_auth_password and ex_force_auth_url with the correct values specific to your installation.

Note

This example works with Libcloud version 0.9.0 and above.

import libcloud.security
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# This assumes you don't have SSL set up.
# Note: Code like this poses a security risk (MITM attack) and
# that's the reason why you should never use it for anything else
# besides testing. You have been warned.
libcloud.security.VERIFY_SSL_CERT = False

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack(
    "your_auth_username",
    "your_auth_password",
    ex_force_auth_url="http://192.168.1.101:5000",
    ex_force_auth_version="2.0_password",
)

Create a VMware vCloud v1.5 node using generic provider

This example demonstrates how to launch a VMware vCloud v1.5 node on a generic provider such as a test lab

Note

This example works with Libcloud version 0.10.1 and above.

import libcloud.security
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# Skip this step if you are launching nodes on an official vCloud
# provider. It is intended only for self signed SSL certs in
# vanilla vCloud Director v1.5 test deployments.
# Note: Code like this poses a security risk (MITM attack) and
# that's the reason why you should never use it for anything else
# besides testing. You have been warned.
libcloud.security.VERIFY_SSL_CERT = False

vcloud = get_driver(Provider.VCLOUD)

driver = vcloud(
    "you username@organisation", "your password", host="vcloud.local", api_version="1.5"
)

# List all instantiated vApps
nodes = driver.list_nodes()
# List all VMs within the first vApp instance
print(nodes[0].extra["vms"])

# List all available vApp Templates
images = driver.list_images()
image = [i for i in images if i.name == "natty-server-cloudimg-amd64"][0]

# Create node with minimum set of parameters
node = driver.create_node(name="test node 1", image=image)
# Destroy the node
driver.destroy_node(node)

# Create node without deploying and powering it on
node = driver.create_node(name="test node 2", image=image, ex_deploy=False)

# Create node with custom CPU & Memory values
node = driver.create_node(name="test node 3", image=image, ex_vm_cpu=3, ex_vm_memory=1024)

# Create node with customised networking parameters (eg. for OVF
# imported images)
node = driver.create_node(
    name="test node 4",
    image=image,
    ex_vm_network="your vm net name",
    ex_network="your org net name",
    ex_vm_fence="bridged",
    ex_vm_ipmode="DHCP",
)

# Create node in a custom virtual data center
node = driver.create_node(name="test node 4", image=image, ex_vdc="your vdc name")

# Create node with guest OS customisation script to be run at first boot
node = driver.create_node(
    name="test node 5", image=image, ex_vm_script="filesystem path to your script"
)

Create EC2 node using a provided key pair and security groups

Note

This example assumes the provided key pair already exists. If the key pair doesn’t exist yet, you can create it using AWS dashboard, or ex_import_keypair() driver method.

This example demonstrates how to create an EC2 node using an existing key pair. Created node also gets added to the provided security groups.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

ACCESS_ID = "your access id"
SECRET_KEY = "your secret key"

SIZE_ID = "t1.micro"

# Name of the existing keypair you want to use
KEYPAIR_NAME = "keypairname"

# A list of security groups you want this node to be added to
SECURITY_GROUP_NAMES = ["secgroup1", "secgroup2"]

cls = get_driver(Provider.EC2)
driver = cls(ACCESS_ID, SECRET_KEY)

sizes = driver.list_sizes()
images = driver.list_images()
size = [s for s in sizes if s.id == "t1.micro"][0]
image = images[0]

node = driver.create_node(
    name="test-node-1",
    image=image,
    size=size,
    ex_keyname=KEYPAIR_NAME,
    ex_securitygroup=SECURITY_GROUP_NAMES,
)

As noted in the example, you use ex_keyname argument to specify key pair name and ex_securitygroup to specify a name of a single (str) or multiple groups (list) you want this node to be added to.

Create EC2 node using a custom AMI

This examples demonstrates how to create an EC2 node using a custom AMI (Amazon Machine Image).

AMI’s are region specific which means you need to select AMI which is available in the region of an EC2 driver you have instantiated.

In Libcloud 0.13.0 and lower, region is determined based on the provider constant (us-east-1 is available as Provider.EC2_US_EAST, us-west-1 is available as Provider.EC2_US_WEST and so on). For a full list of supported providers and provider constants, see supported providers page

from libcloud.compute.base import NodeImage
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

ACCESS_ID = "your access id"
SECRET_KEY = "your secret key"

# Image with Netflix Asgard available in us-west-1 region
# https://github.com/Answers4AWS/netflixoss-ansible/wiki/AMIs-for-NetflixOSS
AMI_ID = "ami-c8052d8d"

SIZE_ID = "t1.micro"

# 'us-west-1' region is available in Libcloud under EC2_US_WEST provider
# constant
cls = get_driver(Provider.EC2)
driver = cls(ACCESS_ID, SECRET_KEY, region="us-west-1")

# Here we select
sizes = driver.list_sizes()
size = [s for s in sizes if s.id == "t1.micro"][0]
image = NodeImage(id=AMI_ID, name=None, driver=driver)

node = driver.create_node(name="test-node", image=image, size=size)

Create EC2 node using an IAM Profile

Note

This example assumes the IAM profile already exists. If the key pair doesn’t exist yet, you must create it manually.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

ACCESS_ID = "your access id"
SECRET_KEY = "your secret key"
IAM_PROFILE = "your IAM profile arn or IAM profile name"

IMAGE_ID = "ami-c8052d8d"
SIZE_ID = "t1.micro"
cls = get_driver(Provider.EC2)
driver = cls(ACCESS_ID, SECRET_KEY, region="us-west-1")

# Here we select size and image
sizes = driver.list_sizes()
images = driver.list_images()

size = [s for s in sizes if s.id == SIZE_ID][0]
image = [i for i in images if i.id == IMAGE_ID][0]

node = driver.create_node(name="test-node", image=image, size=size, ex_iamprofile=IAM_PROFILE)

Create a node on a CloudStack provider using a provided key pair and security groups

Note

This example assumes the provided key pair already exists. If the key pair doesn’t exist yet, you can create it using the provider’s own UI, or ex_create_keypair() driver method. This functionality is only available in Libcloud 0.14.0 and above.

This example demonstrates how to create a node using an existing key pair. Created node also gets added to the provided security groups.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

ACCESS_ID = "your access id"
SECRET_KEY = "your secret key"
HOST = "hostname or ip address of your management server"
PATH = "path to the api endpoint, e.g: /client/api"

SIZE_ID = "id of the computer offering you want to use"
IMAGE_ID = "id of the template you want to use"

# Name of the existing keypair you want to use
KEYPAIR_NAME = "keypairname"

# The security groups you want this node to be added to
SECURITY_GROUP_NAMES = ["secgroup1", "secgroup2"]

cls = get_driver(Provider.CLOUDSTACK)
driver = cls(key=ACCESS_ID, secret=SECRET_KEY, secure=True, host=HOST, path=PATH)

sizes = driver.list_sizes()
images = driver.list_images()
size = [s for s in sizes if s.id == SIZE_ID][0]
image = [i for i in images if i.id == IMAGE_ID][0]

node = driver.create_node(
    name="test-node-1",
    image=image,
    size=size,
    ex_security_groups=SECURITY_GROUP_NAMES,
    ex_keyname=KEYPAIR_NAME,
)

Create floating IP and attach it to a node using a local OpenStack provider

This example demonstrates how to use OpenStack’s floating IPs.

import libcloud.security
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# This assumes you don't have SSL set up.
# Note: Code like this poses a security risk (MITM attack) and
# that's the reason why you should never use it for anything else
# besides testing. You have been warned.
libcloud.security.VERIFY_SSL_CERT = False

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack(
    "your_auth_username",
    "your_auth_password",
    ex_force_auth_url="http://10.0.4.1:5000",
    ex_force_auth_version="2.0_password",
    ex_tenant_name="your_tenant",
)

# get the first pool - public by default
pool = driver.ex_list_floating_ip_pools()[0]

# create an ip in the pool
floating_ip = pool.create_floating_ip()

# get the node, note: change the node id to the some id you have
node = driver.ex_get_node_details("922a4381-a18c-487f-b816-cc31c9060853")

# attach the ip to the node
driver.ex_attach_floating_ip_to_node(node, floating_ip)

# remove it from the node
driver.ex_detach_floating_ip_from_node(node, floating_ip)

# delete the ip
floating_ip.delete()

Create an IBM SCE Windows node using generic provider

Note

ex_configurationData is the key component of this example.

This example shows how to create a Windows node using IBM SmartCloud Enterpiese.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

Driver = get_driver(Provider.IBM)
conn = Driver("user@name.com", "ibm_sce_password")

images = conn.list_images()
image = [i for i in images if i.id == "20014110"][0]

locations = conn.list_locations()
location = [loc for loc in locations if loc.id == "82"][0]

sizes = conn.list_sizes()
size = [s for s in sizes if s.id == "COP32.1/2048/60"][0]

node = conn.create_node(
    name="windows box",
    image=image,
    size=size,
    ex_configurationData={"UserName": "someone", "Password": "Wind0wsPass"},
    location=location,
)
print(conn.list_nodes())