python呼叫 api 雲伺服器組管理
阿新 • • 發佈:2022-04-01
from ast import Return
import re
from HwUser import HwUser
import json
'''
在雲伺服器的/root/huawei 目錄下編寫 create_server_group.py 檔案,並匯入賽項提供的HwUser.py 檔案獲取授權。編寫 Python 程式碼,參考官方相關的API呼叫文件,建立華為雲的雲伺服器組,具體要求為
(1)雲伺服器組名稱:chinaskills_server_group;
(2)雲伺服器組策略:反親和性;
(3)如果安全組已經存在,程式碼中需要先刪除;
(4)建立成功後輸出該雲伺服器組的資訊。
'''
if __name__ == "__main__":
# 1 獲取授權
ak = "7IJFH088K7ZHG6H7MJ7E"
sk = "ClkPa47PpNxEpiPzKQ3c5Nzcb1S5uSVGhQ13owge"
user = HwUser(ak, sk)
# 2 檢查現有的雲伺服器組
print("正在查詢雲伺服器組。。。。", end="")
resp = user.httpRequest("GET", "https://ecs.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/cloudservers/os-server-groups")
result = json.loads(str(resp.content, encoding="utf-8"))
## 2.1 檢視是否已存在雲伺服器組 chinaskills_server_group
### 取出現有的雲伺服器列表
now_net_list = result["server_groups"]
targetID = []
for i in now_net_list:
if "chinaskills_server_group" == i["name"]:
targetID.append(i["id"])
if targetID == []:
print("當前環境未存在chinaskills_server_group")
else:
print("存在需要刪除的雲伺服器組")
print(" 正在嘗試刪除已存在的雲伺服器組chinaskills_server_group。。。")
for id in targetID:
requestURL = "https://ecs.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/cloudservers/os-server-groups/"+id
resp = user.httpRequest("DELETE", requestURL,{ "content-type": "application/json" },"")
print(" 刪除完成")
# 3 建立伺服器組
print("正在建立伺服器組。。。",end="")
name = "chinaskills_server_group"
bodys = json.dumps({"server_group": {"name": name,"policies": ["anti-affinity"]}})
resp = user.httpRequest("POST", "https://ecs.cn-east-2.myhuaweicloud.com/v2.1/0f4115bb9280f3192fa7c00e1c434035/os-server-groups",{ "content-type": "application/json" },bodys)
## 3.1 獲取ID
result = json.loads(str(resp.content, encoding="utf-8"))
yid = result["server_group"]["id"]
print("完成,新伺服器組ID為:"+yid)
# 4 查詢
print("伺服器組資訊查詢中。。。")
resp = user.httpRequest("GET", "https://ecs.cn-east-2.myhuaweicloud.com/v2.1/0f4115bb9280f3192fa7c00e1c434035/os-server-groups/"+yid,{ "content-type": "application/json" }, "")
result = json.loads(str(resp.content, encoding="utf-8"))
print(" 雲伺服器組ID:"+str(result["server_group"]["id"]))
print(" 雲伺服器組策略:"+str(result["server_group"]["policies"]))
print(" 雲伺服器組名字:"+str(result["server_group"]["name"]))