一.1.3.2 Python运维开发:基于Openstack Restful API 实现镜像上传
【摘要】 [root@controller ~]# vi /root/create_image.pyimport requests.json.timecontroller_ip=input("请输入访问openstack平台控制节点IP地址:(xx.xx.xx_xx)\n")image_name="cirros_python"file_path ="/root/cirros-0.3.4-x86_64-...




[root@controller ~]# vi /root/create_image.py
import requests.json.time
controller_ip=input("请输入访问openstack平台控制节点IP地址:(xx.xx.xx_xx)\n")
image_name="cirros_python"
file_path ="/root/cirros-0.3.4-x86_64-disk.img"
try:
url= f"http://{controller_ip}:5000/v3/auth/tokens"
body={
"auth":{
"identity": {
"methods":["password"],
"password": {
"user": {
"domain":{
"name":"demo"
}
"name": "admin",
"password":“000000"
}
}
},
"scope":{
"project": {
"domain": {
"name":"demo"
},.
"name":"admin"
}
}
}
}
headers ={"Content-Type":"application/json"}
Token=requests.post(url, data=json.dumps(body), headers=headers).headers['X-Subject-Token']
headers ={"X-Auth-Token": Token}
except Exception as e:
print(f"获取Token值失败,请检查访问云主机控制节点IP是否正确?输出错误信息如下:{str(e)}”)
exit(0)
class glance_api:
def__init__(self,headers: diet, resUrl: str):
self.headers = headers
self.resUrl = resUrl
#创建zlancc镜像
def create_glance(self, container_format="bare", disk_format="qcow2"):
body ={
"container_format": container_format,
"disk_format": disk_format,
"name":image_name,
}
status_code= requests.post(self.resUrl, data=json.dumps(body), header
s=self.headers).status_code
if(status_code ==201):
return f"创建镜像成功,id为: {glance_api.get_glance_id()}"
else:
return“创建镜像失败”
#获取glance镜像id
def get_glance_id(self):
result= json.loads(requests.get(self.resUrl,headers=self.headers).text)
for item in result['images']:
if(item['name']==image_name):
return item['id']
#上传glance镜像
def update_glance(self):
self.resUrl-selfresUrl+"/"+selfget glance id()+"/file"w
selfheaders['Content-Type"]= "application/octet-stream"e
status code = requests,put(selfresUrl,data=open(file path,'rb’).read(),he
aders=selfhcaders).status code-
ifstatus code == 204):←
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章



评论(0)