Openstack-glance API镜像管理的相关例子:
我的openstack环境变量写在openstack.conf中,
[OPENSTACK]
OS_USERNAME=admin
OS_PASSWORD=Passw0rd
OS_TENANT_NAME=admin
OS_AUTH_URL=http://192.168.122.7:5000/v2.0
OS_REGION_NAME=RegionOne
python-glanceclient API:
class glanceclient.v2.client.Client(endpoint, **kwargs)
Bases: object
Client for the OpenStack Images v2 API.
Parameters:
endpoint (string) – A user-supplied endpoint URL for the glance service.
token (string) – Token for authentication.
timeout (integer) – Allows customization of the timeout for client http requests. (optional)
首先要通过keystone获取glance service的endpoint:
from keystoneclient.v2_0 import client as keystoneclient
from glanceclient.v2 import client as gclient
import ConfigParser
config = ConfigParser.ConfigParser()
conf = open('openstack.conf','r')
config.readfp(conf)
USERNAME = config.get('OPENSTACK','OS_USERNAME')
PASSWORD = config.get('OPENSTACK','OS_PASSWORD')
TENANT_NAME = config.get('OPENSTACK','OS_TENANT_NAME')
AUTH_URL = config.get('OPENSTACK','OS_AUTH_URL')
keystone = keystoneclient.Client(username=USERNAME,password=PASSWORD,tenant_name=TENANT_NAME,auth_url=AUTH_URL)
glance_endpoint = keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
获取client对象:
glance = gclient.Client(glance_endpoint,token=keystone.auth_token)
列出上传的镜像:
images = glance.images.list()
print "=========================================================================================================================="
print "ID Name Disk Format Container Format Size Status"
for i in images:
print ("%-35s %-35s %-15s %-15s %-10d %-4s")%(i.id,i.name,i.disk_format,i.container_format,i.size,i.status)
结果:
创建镜像:
from keystoneclient.v2_0 import client as keystoneclient
import glanceclient
import ConfigParser
config = ConfigParser.ConfigParser()
conf = open('openstack.conf','r')
config.readfp(conf)
USERNAME = config.get('OPENSTACK','OS_USERNAME')
PASSWORD = config.get('OPENSTACK','OS_PASSWORD')
TENANT_NAME = config.get('OPENSTACK','OS_TENANT_NAME')
AUTH_URL = config.get('OPENSTACK','OS_AUTH_URL')
keystone = keystoneclient.Client(username=USERNAME,password=PASSWORD,tenant_name=TENANT_NAME,auth_url=AUTH_URL)
print keystone.auth_token
glance_endpoint = keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
# create and upload an image
glanceClient = glanceclient.Client('1',glance_endpoint,token=keystone.auth_token)
img_url = "/home/stack/hao/cirros-0.3.0-x86_64-disk.img"
with open(img_url,'rb') as img_file:
glanceClient.images.create(name='hao',is_public='True',disk_format='qcow2',container_format='bare',data=img_file)