Python运维开发:基于openstack RestfulAPI上传镜像和创建云主机
Python对接openstack API 上传镜像和创建云主机
基础环境
python 脚本文件头建议加入“ #encoding:utf-8”避免编码错误;测试脚本代码用python3命令执行与测试;在linux系统中安装Python3 并安装request等依赖包
配置:有一台搭建好的open stack平台
导入python源等依赖包
在controller节点/root/目录下编写api_image_manager.py脚本
要求:1.创建镜像(创建之前删除同名镜像)
2.查询镜像
#获取token值
import requests
import json
import time
import argparse
try:
url = "http://192.168.1.101: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}
print(token)
except Exception as e:
print(f"debeat{str(e)}")
exit(0)
#定义class类
class create_glance:
def __init__(self,headers,url):
self.headers=headers
self.url=url
def delete_images(self,image_name):
result = json.loads(requests.get(self.url,headers=self.headers).text)
for i in result['images']:
if i['name'] == image_name:
requests.delete(f"http://192.168.1.101:9292/v2/images/{i['id']}",headers=self.headers)
def create_glance(self,image_name:str,container_format="bare",disk_format="qcow2"):
body = {
"name": image_name,
"container_format": container_format,
"disk_foramt": disk_format
}
status_code = requests.post(self.url,data=json.dumps(body),headers=self.headers)
print(status_code.json['names'])
def get_image_id(self,image_name):
result = json.loads(requests.get(self.url, headers=self.headers).text)
for i in result['images']:
if i['name'] == image_name:
return i['id']
def updata_glance(self,image_name:str,file_path=''):
self.url=self.url+"/"+self.get_image_id(image_name)+'/file'
self.headers['Content-Type'] = 'application/octet-stream'
status_code = requests.put(self.url,data=open(file_path,'rb').read(),headers=self.headers)
def show_image(self,image_name):
result = json.loads(requests.get(self.url, headers=self.headers).text)
for i in result['images']:
if i['name'] == image_name:
return i['id']
create_glance=create_glance(headers,"http://192.168.1.101:9292/v2/images")
create_glance.delete_images("giant fox")
create_glance.create_glance("giant fox")
print(create_glance.show_image("giant fox"))
create_glance.updata_glance('giant fox',file_path="./CentOS_7.5_x86_64_XD.qcow2")
创建镜像时 可能会出现一直排队的情况 在创建虚拟机时可以使用已经在运行的镜像
+--------------------------------------+-----------+--------+
| ID | Name | Status |
+--------------------------------------+-----------+--------+
| 0eede4fd-be01-4508-9f21-7089bc166a26 | centos | active |
| 36fc6cfc-9ad1-4189-9522-d8addccafa60 | giant fox | queued |
+--------------------------------------+-----------+--------+
创建一台云主机镜像已经创建好,其他的自行创建
import json
import requests
import time
try:
url = "http://192.168.1.101: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,json.dumps(body),headers=headers).headers["X-Subject-Token"]
headers = {"X-Auth-Token":Token}
print(Token)
except Exception as e:
print(f"失败信息如下:{str(e)}")
exit(0)
class create_vm:
def __init__(self,headers):
self.headers=headers
def delete_vm(self):
result = requests.get("http://192.168.1.101:8774/v2.1/servers",headers=self.headers)
for i in result.json()['servers']:
if i['name'] == 'test_vm':
requests.delete(f"http://192.168.1.101:8774/v2.1/servers/{i['id']}",headers=self.headers)
def get_image_id(self):
result = requests.get("http://192.168.1.101:9292/v2/images",headers=self.headers)
for i in result.json()['images']:
if i['name'] == "giant fox":
self.image_id=i['id']
def get_network_id(self):
result = requests.get("http://192.168.1.101:9696/v2.0/networks",headers=self.headers)
for i in result.json()['networks']:
if i['name'] == 'network':
self.network_id=i['id']
def get_flavor_id(self):
result = requests.get("http://192.168.1.101:8774/v2.1/flavors",headers=self.headers)
for i in result.json()['flavors']:
if i['names'] == '4g4u100g':
self.flavor_id=i['id']
def create_vm(self):
self.delete_vm()
self.get_flavor_id()
self.get_image_id()
self.get_network_id()
data = {
"server": {
"name": "test_vm",
"imageRef": self.image_id,
"flavorRef": self.flavor_id,
"networks": [{'uuid':self.network_id}]
}
}
status_code = requests.post("http://192.168.1.101:8774/v2.1/servers",headers=self.headers,data=json.dumps(data))
print(status_code.json())
create_vm=create_vm(headers=headers)
create_vm.create_vm()
创建成功
+--------------------------------------+---------+--------+----------------------+--------+----------+
| ID | Name | Status | Networks | Image | Flavor |
+--------------------------------------+---------+--------+----------------------+--------+----------+
| f2d7a396-9bec-4074-9e35-c39e4d556756 | test_vm | ACTIVE | network=192.168.1.7 | centos | 4g4u100g
更多推荐
所有评论(0)