您当前的位置:首页 > 学海无涯 > 心得笔记网站首页心得笔记
蓝鲸项目菜单处理脚本
发布时间:2021-01-10作者:♂逸風★淩軒
源码:
# -*- coding: utf-8 -*- import requests import json import sys import os import stat import re from configobj import ConfigObj #python3下注释以下两行 reload(sys) sys.setdefaultencoding('utf-8') cur_path=os.path.dirname(os.path.realpath(__file__)) #获取config.ini的路径 config_path=os.path.join(cur_path,'config.ini') config = ConfigObj(config_path) # 蓝鲸paas URL BK_PAAS_HOST = "地址" # 应用ID APP_CODE = 'bk_sops' # 安全密钥(应用 TOKEN),可以通过 蓝鲸智云开发者中心 -> 点击应用ID -> 基本信息 获取 APP_TOKEN = 'token' # 系统的唯一标识, 在"蓝鲸CMDB"->"模型管理"->"模型"->"系统"->"唯一标识"获取 SYS_OBJ = 'sub_system' TYPE= config['type']['action'] BUSINESS_NAME= config['s_insconfig']['business_name'] SOURCE_SYS= config['s_insconfig']['source_sys'] TARGET_SYS= config['t_insconfig']['target_sys'] TARGET_BUSINESS_NAME= config['t_insconfig']['target_business_name'] SOURCE_SET = config['moderconfig']['source_set'] TARGET_SET = config['moderconfig']['target_set'] OPENPREFIX = config['match']['openprefix'] PREFIX = config['match']['prefix'] ATTR = config['match']['attr'] IP_LIST = config['host_list']['delete_host_list'] GZTXY = config['idc_ipr']['gztxy'] SZPBS = config['idc_ipr']['szpbs'] SZZB = config['idc_ipr']['szzb'] SZTYY = config['idc_ipr']['sztyy'] GZTYY = config['idc_ipr']['gztyy'] ZBOFFICE = config['idc_ipr']['zboffice'] BJOFFICE = config['idc_ipr']['bjoffice'] NSOFFICE = config['idc_ipr']['nsoffice'] TWOFFICE = config['idc_ipr']['twoffice'] def search_obj_attr(object_id): # 获取对象字段,避免隐藏字段错误 url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_object_attribute/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_obj_id": object_id, "bk_supplier_account":"0" } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return [o['bk_property_id'] for o in res['data']] def search_business(business_name): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_business/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "fields": [ "bk_biz_id", "bk_biz_name" ], "condition": { "bk_biz_name": business_name } } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def search_inst(inst_name,bk_biz_id): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_inst/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_obj_id': SYS_OBJ, "bk_supplier_account": "0", "condition": { SYS_OBJ: [ { "field": "bk_inst_name", "operator": "$eq", "value": inst_name.encode('utf-8') }, { "field": "bk_parent_id", "operator": "$eq", "value": bk_biz_id } ] } } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def search_inst_list(bk_biz_id): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_inst/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_obj_id': SYS_OBJ, "bk_supplier_account": "0", "condition": { SYS_OBJ: [ { "field": "bk_parent_id", "operator": "$eq", "value": bk_biz_id } ] } } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def search_inst_by_object(BK_OBJ_ID): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_inst/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_obj_id": BK_OBJ_ID, "bk_supplier_account": "0", "fields":[], "condition": {} } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def search_inst_by_insid(): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_inst/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_obj_id": "room", "bk_supplier_account": "0" } rp = requests.post(url=url, data=json.dumps(params), verify=False) print(json.loads(rp.content)) def search_set(parent_id, bk_biz_id): """ :param parent_id: 系统ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_set/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id, "condition": { "bk_parent_id": parent_id } } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def search_module(set_id, bk_biz_id): """ 查询模块 :param set_id: 集群ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_module/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_set_id': set_id, 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def create_inst(bk_biz_id,bk_inst_name,detail): """ 创建实例 :param bk_biz_id: 业务ID """ # 定义参数字典 field_dict = {} # 获取字段列表 for i in search_obj_attr(SYS_OBJ): if i != 'bk_inst_name' and i != 'bk_biz_id' and i != 'bk_parent_id': field_dict[i] = detail.get(i, None) url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/create_inst/') params = { "bk_inst_name": TARGET_SYS, 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_obj_id': SYS_OBJ, "bk_inst_name": bk_inst_name.encode('utf-8'), 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id, 'bk_parent_id': bk_biz_id } params.update(**field_dict) rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res def create_set(bk_biz_id, bk_parent_id, detail): """ 创建集群 :param bk_biz_id: 业务ID :param bk_parent_id: 系统实例ID """ # 定义参数字典 field_dict = {'bk_parent_id':bk_parent_id} # 获取字段列表 for i in search_obj_attr('set'): field_dict[i] = detail.get(i, None) url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/create_set/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id, } params.update(data=field_dict) rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) # return res['data']['info'] return res def create_module(bk_biz_id, bk_parent_id, detail): """ 创建模块 :param bk_biz_id: 业务ID :param bk_parent_id: 集群ID """ # 定义参数字典 field_dict = {'bk_parent_id':bk_parent_id} # 获取字段列表 for i in search_obj_attr('module'): field_dict[i] = detail.get(i, None) url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/create_module/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id, 'bk_set_id': bk_parent_id } params.update(data=field_dict) rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res def update_inst(bk_biz_id,bk_inst_id,bk_inst_name,tag='dev'): """ 更新实例 :param bk_inst_id: 集群ID """ # 获取字段列表 url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/update_inst/') params = { "bk_inst_name": TARGET_SYS, 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_obj_id': SYS_OBJ, 'bk_supplier_account': '0', 'bk_inst_id': bk_inst_id, 'bk_parent_id': bk_biz_id, "bk_inst_name": bk_inst_name.encode('utf-8'), 'tag': tag } headers = { 'bk_biz_id': str(bk_biz_id), 'content-type': 'application/json', } rp = requests.post(url=url,headers=headers, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) # return res['data']['info'] return res def update_inst_by_object(BK_OBJ_ID,bk_cloud_id,bk_cloud_name): url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/update_inst/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_obj_id": BK_OBJ_ID, "bk_supplier_account": "0", 'bk_cloud_id': bk_cloud_id, "bk_cloud_name": bk_cloud_name.encode('utf-8') } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res['data']['info'] def delete_host(bk_host_id): """ 删除主机 :param bk_biz_id: 业务ID :param bk_host_id: 主机ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/delete_host/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "bk_host_id":bk_host_id } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) if res["message"] == "success": print("----删除主机成功\n") else: print("----删除主机失败,原因:%s \n"%(res["message"])) sys.exit() def transfer_host_module(bk_biz_id,bk_host_id,bk_module_id,is_increment=True): """ 分配主机到模块 :param bk_biz_id: 业务ID :param bk_host_id: 主机ID :param bk_module_id: 模块ID :param is_increment: 覆盖或者追加,会删除原有关系. true是更新,false是覆盖 """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/transfer_host_module/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', 'bk_supplier_account': '0', 'bk_biz_id': bk_biz_id, "bk_host_id": [bk_host_id], "bk_module_id": [bk_module_id], "is_increment": is_increment } rp = requests.post(url=url, data=json.dumps(params), verify=False) if rp.status_code != 200: raise Exception('{} error'.format(rp.status_code)) res = json.loads(rp.content) if not res['result']: raise Exception('{} error'.format(res['message'])) return res def transfer_host_to_idlemodule(bk_host_id,bk_biz_id): """ 分配主机到业务空闲主机模块 :param bk_biz_id: 业务ID :param bk_host_id: 主机ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/transfer_host_to_idlemodule/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "bk_biz_id": bk_biz_id, "bk_host_id":[bk_host_id] } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) if res["message"] == "success": print("----移动主机到空闲资源池成功\n") else: print("----移动主机到空闲资源池失败,原因:%s \n"%(res["message"])) sys.exit() def transfer_host_to_resourcemodule(bk_host_id,bk_biz_id): """ 分配主机到资源池模块 :param bk_biz_id: 业务ID :param bk_host_id: 主机ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/transfer_host_to_resourcemodule/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "bk_biz_id": bk_biz_id, "bk_host_id":[bk_host_id] } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) if res["message"] == "success": print("----移动主机到资源池成功") else: print("----移动主机到资源池失败,原因:%s \n"%(res["message"])) sys.exit() def search_host_ip(IP,type="1",start=0,limit=10): """ 根据IP查询主机分配情况 :param IP: 主机IP """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_host/') if type == "1": params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "ip": { "data": [IP], "exact": 1, "flag": "bk_host_innerip|bk_host_outerip" }, "condition": [ { "bk_obj_id":"module", "fields":[], "condition":[] }, { "bk_obj_id":"biz", "fields":[], "condition":[] } ], "page": { "start": start, "limit": limit, "sort": "bk_host_id" }, "pattern": "" } elif type == "2": params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "ip": { "data": [IP], "exact": 1, "flag": "bk_host_innerip|bk_host_outerip" }, "condition": [ { "bk_obj_id":"host", "fields":[], "condition":[] } ], "page": { "start": start, "limit": limit, "sort": "bk_host_id" }, "pattern": "" } elif type == "3": params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "ip": { "data": [], "exact": 0, "flag": "bk_host_innerip|bk_host_outerip" }, "condition": [ { "bk_obj_id":"host", "fields":[], "condition":[] } ], "page": { "start": start, "limit": limit, "sort": "bk_host_id" }, "pattern": "" } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) return res def search_host_module(bk_module_id): """ 根据模块ID查询模块关联主机 :param bk_module_id: 模块ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/search_host/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "condition": [ { "bk_obj_id": "host", "fields": [], "condition": [] }, { "bk_obj_id":"module", "fields":[], "condition":[] }, { "bk_obj_id": "module", "fields": [], "condition": [ { "field": "bk_module_id", "operator": "$eq", "value": bk_module_id } ] } ], "page": { "start": 0, "limit": 10, "sort": "bk_host_id" }, "pattern": "" } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) return res def get_inst_tag(TARGET_SYS): if TARGET_SYS.encode('utf-8') == "联调环境": tag = 'debug' elif TARGET_SYS.encode('utf-8') == "测试环境": tag = 'test' elif TARGET_SYS.encode('utf-8') == "压测环境": tag = 'str' elif TARGET_SYS.encode('utf-8') == "uat环境": tag = 'uat' elif TARGET_SYS.encode('utf-8') == "生产环境": tag = 'prd' elif TARGET_SYS.encode('utf-8') == "培训环境": tag = 'train' else: tag = 'dev' return tag def update_host(bk_host_id,idc_id): """ 更新主机模块 :param bk_host_id: 主机ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/cc/update_host/') if idc_id == 2: physical_position = "腾讯云" elif idc_id == 3 : idc_id = 0 physical_position = "鹏博士" elif idc_id == 4 : physical_position = "深圳天翼云" elif idc_id == 6 : physical_position = "深圳总部" elif idc_id == 7 : idc_id = 4 physical_position = "广州天翼云" else: idc_id = 0 physical_position = "默认区域" params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "bk_host_id":bk_host_id, 'bk_obj_id':'plat', "data": { "physical_position": physical_position.encode('utf-8'), "bk_cloud_id": idc_id } } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) if res["message"] != "success": print("----更新主机%s资源失败,原因:%s \n"%(bk_host_id,res["message"])) sys.exit() def get_agent_status(bk_cloud_id,ip): """ 查询agent实时在线状态 :param bk_cloud_id: 云区域ID """ url = '{0}{1}'.format(BK_PAAS_HOST, '/api/c/compapi/v2/gse/get_agent_status/') params = { 'bk_app_code': APP_CODE, 'bk_app_secret': APP_TOKEN, 'username': 'admin', "bk_supplier_account": "0", "hosts": [ { "ip": ip, "bk_cloud_id": bk_cloud_id } ] } rp = requests.post(url=url, data=json.dumps(params), verify=False) res = json.loads(rp.content) if res["message"] != "success": print("----查询主机%sAgent状态失败,原因:%s \n"%(bk_host_id,res["message"])) sys.exit() return res if __name__ == '__main__': # 查询业务ID biz_list = search_business(BUSINESS_NAME) if biz_list == []: raise Exception('错误!未找到{}业务'.format(BUSINESS_NAME)) for b in biz_list: if b['bk_biz_name'] == BUSINESS_NAME: bk_biz_id = b['bk_biz_id'] # 查询业务下系统 s_inst_dict = search_inst(SOURCE_SYS,bk_biz_id) for inst in s_inst_dict: if inst.get("bk_parent_id",9999999) == bk_biz_id and inst.get("bk_inst_name",999999999).encode('utf-8') == SOURCE_SYS.encode('utf-8'): s_bk_inst_id = inst["bk_inst_id"] if TYPE == "1": t_inst_dict = search_inst(TARGET_SYS,bk_biz_id) t_bk_inst_id = 0 for inst in t_inst_dict: if inst.get("bk_parent_id",9999999) == bk_biz_id and inst.get("bk_inst_name",999999999).encode('utf-8') == TARGET_SYS.encode('utf-8'): t_bk_inst_id = inst["bk_inst_id"] if t_bk_inst_id : print("%s环境已经存在,进入集群克隆模式"%(TARGET_SYS)) else: print("%s环境不存在,进入环境克隆模式"%(TARGET_SYS)) # 创建环境 print("-- 创建环境:{}".format(TARGET_SYS)) t_inst_data = create_inst(bk_biz_id,TARGET_SYS,s_inst_dict[0]) t_bk_inst_id = t_inst_data['data']['bk_inst_id'] update_inst(bk_biz_id,t_bk_inst_id,TARGET_SYS,get_inst_tag(TARGET_SYS)) s_bk_set_list = search_set(s_bk_inst_id, bk_biz_id) t_bk_set_list = search_set(t_bk_inst_id, bk_biz_id) t_bk_set_name_list = [] for t_bk_set in t_bk_set_list: t_bk_set_name_list.append(t_bk_set['bk_set_name']) for s_bk_set in s_bk_set_list: s_set_id = s_bk_set['bk_set_id'] if s_bk_set['bk_set_name'] not in t_bk_set_name_list: print(" |-- 创建集群:{}".format(s_bk_set['bk_set_name'])) t_set_data = create_set(bk_biz_id, t_bk_inst_id, s_bk_set) t_set_id = t_set_data['data']['bk_set_id'] for s_module in search_module(s_set_id, bk_biz_id): print(" |-- 创建模块:{}".format(s_module['bk_module_name'])) create_module(bk_biz_id, t_set_id, s_module) else: for t_bk_set in t_bk_set_list: if s_bk_set['bk_set_name'] == t_bk_set['bk_set_name']: print(" |-- 已存在集群:{}".format(s_bk_set['bk_set_name'])) t_set_id = t_bk_set['bk_set_id'] t_module_name_list = [] for t_module in search_module(t_set_id, bk_biz_id): t_module_name_list.append(t_module['bk_module_name']) for s_module in search_module(s_set_id, bk_biz_id): if s_module['bk_module_name'] not in t_module_name_list: print(" |-- 创建模块:{}".format(s_module['bk_module_name'])) create_module(bk_biz_id, t_set_id, s_module) elif TYPE == "2": if s_bk_inst_id: bk_set_list = search_set(s_bk_inst_id, bk_biz_id) for bk_set in bk_set_list: if bk_set['bk_set_name'] == SOURCE_SET: s_set_id = bk_set['bk_set_id'] elif bk_set['bk_set_name'] == TARGET_SET: t_set_id = bk_set['bk_set_id'] # 查询目标模块 t_module_name_list = [] t_module_id_list = [] for t_module in search_module(t_set_id, bk_biz_id): t_module_name_list.append(t_module['bk_module_name']) t_module_id_list.append(t_module['bk_module_id']) # 查询源模块 s_module_name_list = search_module(s_set_id, bk_biz_id) print("迁移%s环境%s集群模块到%s集群"%(SOURCE_SYS,SOURCE_SET,TARGET_SET)) for s_module in s_module_name_list: if s_module['bk_module_name'] not in t_module_name_list: if OPENPREFIX == "1": if s_module['bk_module_name'].startswith(PREFIX): print(" |--匹配%s*模型创建模块:%s"%(PREFIX,s_module['bk_module_name'])) t_module_info = create_module(bk_biz_id, t_set_id, s_module) t_module_id = t_module_info['data']['bk_module_id'] s_host_list = search_host_module(s_module['bk_module_id']) for s_host in s_host_list['data']['info']: transfer_host_module(bk_biz_id,s_host["host"]['bk_host_id'],t_module_id) else: print(" |--增量型创建模块:{}".format(s_module['bk_module_name'])) t_module_info = create_module(bk_biz_id, t_set_id, s_module) t_module_id = t_module_info['data']['bk_module_id'] s_host_list = search_host_module(s_module['bk_module_id']) for s_host in s_host_list['data']['info']: s_bk_host_id = s_host["host"]['bk_host_id'] transfer_host_module(bk_biz_id,s_bk_host_id,t_module_id) elif TYPE == "3": for IP in IP_LIST: p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$') if p.match(IP): print("处理主机%s"%(IP)) res = search_host_ip(IP,type="1",start=0,limit=1) if res['data']['count'] == 0: print("----IP %s 蓝鲸查无结果,请确认是否存在" %(IP)) elif res['data']['count'] == 1: bk_host_id = res['data']['info'][0]['host']['bk_host_id'] if len(res['data']['info'][0]['biz']): bk_biz_id = res['data']['info'][0]['biz'][0]['bk_biz_id'] if len(res['data']['info'][0]['module']): transfer_host_to_idlemodule(bk_host_id,bk_biz_id) if bk_biz_id != 1: #蓝鲸空闲集群ID transfer_host_to_resourcemodule(bk_host_id,bk_biz_id) delete_host(bk_host_id) else: print("----IP无绑定业务直接删除") delete_host(bk_host_id) else: print("----IP蓝鲸存在重复结果,请确认IP状态") else: print(IP, "is not a IP!") elif TYPE == "4": info = search_host_ip(IP="",type="3",start=0,limit=2) count = info['data']['count'] host_id_pbs_list = [] host_id_txy_list = [] host_id_szzb_list = [] host_id_gztyy_list = [] host_id_sztyy_list = [] host_id_default_list = [] ip_list = [] ip_repeat = [] idc_error = [] for i in range(0, count): host_info = search_host_ip(IP="",type="3",start=i,limit=1) host_id = host_info['data']['info'][0]['host']['bk_host_id'] ip = host_info['data']['info'][0]['host']['bk_host_innerip'] host_idc = host_info['data']['info'][0]['host']['bk_cloud_id'][0]['bk_inst_id'] bk_os_name = host_info['data']['info'][0]['host']['bk_os_name'] if ip not in ip_list: ip_list.append(ip) else: ip_repeat.append(ip) ipstr = str(re.findall(r'(?<!\d)\d{1,3}\.\d{1,3}(?=\.\d)', ip)[0]) if ipstr in GZTXY : host_id_txy_list.append(host_id) if host_idc != 2: idc_error.append(str('GZTXY ' + str(ip).ljust(15,' ') + ' IDC' + str(host_idc) +' os:' + str(bk_os_name))) elif ipstr in SZPBS : host_id_pbs_list.append(host_id) if host_idc != 3 and host_idc != 0: idc_error.append(str('SZPBS ' + str(ip).ljust(15,' ') + ' IDC' + str(host_idc) +' os:' + str(bk_os_name))) elif ipstr in SZZB : host_id_szzb_list.append(host_id) if host_idc != 6: idc_error.append(str('SZZB ' + str(ip).ljust(15,' ') + ' IDC' + str(host_idc) +' os:' + str(bk_os_name))) elif ipstr in GZTYY : host_id_gztyy_list.append(host_id) if host_idc != 7 and host_idc != 4: idc_error.append(str('GZTYY ' + str(ip).ljust(15,' ') + ' IDC' + str(host_idc) +' os:' + str(bk_os_name))) elif ipstr in SZTYY : host_id_sztyy_list.append(host_id) if host_idc != 4 and host_idc != 7: idc_error.append(str('SZTYY ' + str(ip).ljust(15,' ') + ' IDC' + str(host_idc) +' os:' + str(bk_os_name))) else: host_id_default_list.append(host_id) host_id_sztyy_list.append(host_id) if host_idc != 0: idc_error.append(str('Defult ' + str(ip) + ' IDC' + str(host_idc)+' os:' + str(bk_os_name))) #search_inst_by_object(bk_obj_id="room") #2"腾讯云" 3"鹏博士" 4"深圳天翼云" 6"深圳总部" 7"广州天翼云" 0"默认区域" for host_id in host_id_pbs_list: update_host(host_id,idc_id=3) for host_id in host_id_txy_list: update_host(host_id,idc_id=2) for host_id in host_id_szzb_list: update_host(host_id,idc_id=6) for host_id in host_id_sztyy_list: update_host(host_id,idc_id=4) for host_id in host_id_gztyy_list: update_host(host_id,idc_id=7) for host_id in host_id_default_list: update_host(host_id,idc_id=0) for ip in ip_repeat: with open('ip_repeat.txt','a') as f: f.write(ip+ '\n') f.close() for idc in idc_error: with open('idc_error.txt','a') as f: f.write(idc+ '\n') f.close() elif TYPE == "5": info = search_host_ip(IP="",type="3",start=0,limit=2) count = info['data']['count'] agent_error = [] for i in range(0, count): host_info = search_host_ip(IP="",type="1",start=i,limit=1) ip = host_info['data']['info'][0]['host']['bk_host_innerip'] bk_cloud_id = host_info['data']['info'][0]['host']['bk_cloud_id'][0]['bk_inst_id'] bk_os_name = host_info['data']['info'][0]['host']['bk_os_name'] bk_biz_name = host_info['data']['info'][0]['biz'][0]['bk_biz_name'] status_info = get_agent_status(bk_cloud_id,ip) key = str(str(bk_cloud_id)+':'+str(ip)) status = status_info['data'][key]['bk_agent_alive'] if status != 1 : agent_error.append(str(str(ip).ljust(50,' ') + str(bk_biz_name).ljust(50,' ')+ str(bk_cloud_id).ljust(50,' ')+str(bk_os_name))) for ip in agent_error: with open('agent_error.txt','a') as f: f.write(ip+ '\n') f.close() elif TYPE == "6": # 查询来源业务ID s_biz_list = search_business(BUSINESS_NAME) if s_biz_list == []: raise Exception('错误!未找到{}业务'.format(BUSINESS_NAME)) for s in s_biz_list: if s['bk_biz_name'] == BUSINESS_NAME: s_bk_biz_id = s['bk_biz_id'] # 查询目标业务ID t_biz_list = search_business(TARGET_BUSINESS_NAME) if t_biz_list == []: raise Exception('错误!未找到{}业务'.format(TARGET_BUSINESS_NAME)) for t in t_biz_list: if t['bk_biz_name'] == TARGET_BUSINESS_NAME: t_bk_biz_id = t['bk_biz_id'] # 查询来源业务下系统 s_inst_dict_list = search_inst_list(s_bk_biz_id) s_bk_inst_list = [] for inst in s_inst_dict_list: s_bk_inst_id = inst["bk_inst_id"] s_bk_inst_name = inst["bk_inst_name"].encode('utf-8') t_inst_dict = search_inst(s_bk_inst_name,t_bk_biz_id) t_bk_inst_id = 0 for inst in t_inst_dict: if inst.get("bk_parent_id",9999999) == t_bk_biz_id and inst.get("bk_inst_name",999999999).encode('utf-8') == s_bk_inst_name.encode('utf-8'): t_bk_inst_id = inst["bk_inst_id"] if t_bk_inst_id : print("%s环境已经存在,进入集群克隆模式"%(s_bk_inst_name)) else: print("%s环境不存在,进入环境克隆模式"%(s_bk_inst_name)) # 创建环境 print("-- 创建环境:{}".format(s_bk_inst_name)) t_inst_data = create_inst(t_bk_biz_id,s_bk_inst_name,inst) t_bk_inst_id = t_inst_data['data']['bk_inst_id'] update_inst(t_bk_biz_id,t_bk_inst_id,s_bk_inst_name,get_inst_tag(s_bk_inst_name)) s_bk_set_list = search_set(s_bk_inst_id, s_bk_biz_id) t_bk_set_list = search_set(t_bk_inst_id, t_bk_biz_id) t_bk_set_name_list = [] for t_bk_set in t_bk_set_list: t_bk_set_name_list.append(t_bk_set['bk_set_name']) for s_bk_set in s_bk_set_list: s_set_id = s_bk_set['bk_set_id'] if s_bk_set['bk_set_name'] not in t_bk_set_name_list: print(" |-- 创建集群:{}".format(s_bk_set['bk_set_name'])) t_set_data = create_set(t_bk_biz_id, t_bk_inst_id, s_bk_set) t_set_id = t_set_data['data']['bk_set_id'] for s_module in search_module(s_set_id, s_bk_biz_id): if ATTR == "1" : if s_module.get("jenkins_tag",0): s_module['jenkins_tag'] = s_module['jenkins_tag']+'-docker' s_module['jar_name'] = s_module['bk_module_name'].replace('.jar','') s_module['jar_name'] = s_module['jar_name'].replace('_','-') s_module['bk_module_name'] = s_module['bk_module_name'].replace('.jar','.img') s_module['bk_module_name'] = s_module['bk_module_name'].replace('_','-') print(" |-- 创建替换docker模块:{}".format(s_module['bk_module_name'].replace('.jar','.img'))) else: print(" |-- 创建模块:{}".format(s_module['bk_module_name'])) create_module(t_bk_biz_id, t_set_id, s_module) else: for t_bk_set in t_bk_set_list: if s_bk_set['bk_set_name'] == t_bk_set['bk_set_name']: print(" |-- 已存在集群:{}".format(s_bk_set['bk_set_name'])) t_set_id = t_bk_set['bk_set_id'] t_module_name_list = [] for t_module in search_module(t_set_id, t_bk_biz_id): t_module_name_list.append(t_module['bk_module_name']) for s_module in search_module(s_set_id, s_bk_biz_id): if s_module['bk_module_name'] not in t_module_name_list and s_module['bk_module_name'].replace('.jar','.img') not in t_module_name_list: if ATTR == "1" : if s_module.get("jenkins_tag",0): s_module['jenkins_tag'] = s_module['jenkins_tag']+'-docker' s_module['jar_name'] = s_module['bk_module_name'].replace('.jar','') s_module['jar_name'] = s_module['jar_name'].replace('_','-') s_module['bk_module_name'] = s_module['bk_module_name'].replace('.jar','.img') s_module['bk_module_name'] = s_module['bk_module_name'].replace('_','-') print(" |-- 创建替换docker模块:{}".format(s_module['bk_module_name'].replace('.jar','.img'))) else: print(" |-- 创建模块:{}".format(s_module['bk_module_name'])) create_module(t_bk_biz_id, t_set_id, s_module)
对应调用配置文件
[type] #初始化系统需要执行yum install python-pip -y && pip install requests #1为环境克隆模式,可以全量或增量克隆SOURCE_SYS环境到TARGET_SYS环境 #2为集群内克隆模式,负责克隆环境内各集群的模块管理 #3为删除已下线主机模式 #4为变更IPIDC区域云区域模块关联 #5为输出错误Agent状态列表 action = 6 [s_insconfig] # 业务名称(type1或者2均需要修改项目) business_name = AI项目 #指定复制前后的系统名称(type1或者2均需要修改项目) source_sys = Dev [t_insconfig] #指定复制后的环境名称(type1需要修改项目) target_sys = Tst # 对传业务名称(type6需要修改项目) target_business_name = AI项目2 [moderconfig] #指定复制前的环境名称(type2需要修改项目) source_set = 合单 #指定复制后的环境名称(type2需要修改项目) target_set = 跟车 [match] #同环境内是否开启精准匹配迁移集群,action参数必须为2,0为不开启迁移所有,1位开启只迁移prefix开头的模块(如非匹配迁移无须修改项目) openprefix = 1 prefix = coo- #是否开启模块属性替换(type6需要修改项目,1位开启,2为不开启) attr = 1 [host_list] #待删除下线主机列表 delete_host_list = 1.1.1.1,2.2.2.2 [idc_ipr] #广州腾讯云 gztxy = 10.124,10.125,10.126,10.127 #深圳鹏博士 szpbs = 10.120,10.121,10.122,10.123 #深圳总部 szzb = 10.80,10.100,10.3,10.81 #广州天翼云 gztyy = 10.20 #深圳天翼云 sztyy = 10.75 #总部办公室 zboffice = 10.32 #北京办公室 bjoffice 10.10 #南山 nsoffice = 10.31 #塘尾 twoffice = 10.36
关键字词:蓝鲸,菜单

上一篇:70个经典的 Shell 脚本
相关文章
-
无相关信息