为了方便,可先自定义一个函数 放在credentials.py里面
# vi credentials.py
#!/usr/bin/env python
import os
def get_keystone_creds():
d = {}
d['username'] =os.environ['OS_USERNAME']
d['password'] =os.environ['OS_PASSWORD']
d['auth_url'] =os.environ['OS_AUTH_URL']
d['tenant_name'] = os.environ['OS_TENANT_NAME']
return d
def get_nova_creds():
d = {}
d['username'] =os.environ['OS_USERNAME']
d['api_key'] =os.environ['OS_PASSWORD']
d['auth_url'] =os.environ['OS_AUTH_URL']
d['project_id']= os.environ['OS_TENANT_NAME']
return d
使用API时
import keystoneclient.v2_0.client as ksclient
import glanceclient
import glanceclient.v2.client as glclient
from credentials import get_keystone_creds
(1)查询虚拟机信息
images = glance.images.list() 获取img 的队列
images.next() 依次输出
部分代码:
creds = get_keystone_creds()
keystone = ksclient.Client(**creds)
glance_endpoint=keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
glance = glclient.Client(glance_endpoint,token=keystone.auth_token)
images = glance.images.list()
print images
print images.next()
(2)上传img
with open(img_url) as fimage: #img_url 镜像存放路径
glance.images.create(name="cirros_zy",is_public=True,disk_format="qcow2",container_format="bare",data=fimage)
部分代码:
keystone = ksclient.Client(**creds)
glance_endpoint=keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
glance=glanceclient.Client('1',glance_endpoint,token=keystone.auth_token)
with open(img_url) as fimage:
glance.images.create(name="cirros_zy",is_public=True,disk_format="qcow2",container_format="bare",data=fimage)
(3)删除img
glance.images.delete(image_id)
(4)成员绑定
glance.image_members.create(image_id,mem_id,can_share=True)
(5)成员删除
glance.image_members.delete(image_id,mem_id)
(6)img 下载
由于glance v2 没有支持镜像下载的API 所以直接使用命令行的方式下载
代码如下:
Import os
string_1 = 'glance image-download --file ' + image_url +' ' + image_id
os.system(string_1)