84 lines
3.8 KiB
Python
84 lines
3.8 KiB
Python
import os, yaml
|
||
from datetime import datetime
|
||
from utils.logger import logger
|
||
|
||
|
||
def load_config():
|
||
"""加载 YAML 配置文件并解析其内容"""
|
||
try:
|
||
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
|
||
raw_config = yaml.safe_load(f)
|
||
|
||
# 全局配置
|
||
global_config = raw_config.get('global', {})
|
||
|
||
# 读取定时任务配置(带默认值)
|
||
schedule_config = global_config.get('schedule', {})
|
||
export_schedule = schedule_config.get('export', {'day_of_week': 'sat','hour': 4,'minute': 0, 'second': 0})
|
||
delete_schedule = schedule_config.get('delete', {'day_of_week': 'sat', 'hour': 19, 'minute': 0, 'second': 0})
|
||
|
||
config = {
|
||
# vCenter/ESXi节点列表
|
||
"MANAGEMENT_NODES": raw_config.get('management_nodes', []),
|
||
"SNAPSHOT_RETENTION_DAYS": int(global_config.get('snapshot_retention_days', 15)),
|
||
"EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', os.path.join(DATA_DIR, f'vm_snapshots_report-{datetime.now().strftime('%Y-%m-%d')}.xlsx')),
|
||
"YAML_OUTPUT_PATH": global_config.get('yaml_output_path', os.path.join(DATA_DIR, f'old_snapshots-{datetime.now().strftime('%Y-%m-%d')}.yaml')),
|
||
"DISABLE_SSL_VERIFY": global_config.get('disable_ssl_verify', True),
|
||
"SCHEDULE_EXPORT": export_schedule,
|
||
"SCHEDULE_DELETE": delete_schedule,
|
||
}
|
||
|
||
# 验证配置
|
||
if not config["MANAGEMENT_NODES"]:
|
||
raise ValueError("未配置任何管理节点(vCenter 或 ESXi),至少要有一台 management_nodes 节点。")
|
||
|
||
# 检查每个节点的必填字段
|
||
required_fields = ['type', 'name', 'host', 'user', 'password', 'max_delete_concurrent']
|
||
for node in config["MANAGEMENT_NODES"]:
|
||
missing = [f for f in required_fields if f not in node]
|
||
if missing:
|
||
raise ValueError(f"节点 {node.get('name', '未知')} 缺少配置字段: {missing}")
|
||
# 验证类型合法性
|
||
if node['type'] not in ['vcenter', 'esxi']:
|
||
raise ValueError(f"节点 {node['name']} 类型错误(仅支持 vcenter 或 esxi)")
|
||
|
||
logger.info(f"✅ 成功加载配置,共 {len(config['MANAGEMENT_NODES'])} 个管理节点")
|
||
return config
|
||
except Exception as e:
|
||
logger.error(f"❌ 加载配置失败: {str(e)}")
|
||
raise
|
||
|
||
|
||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 获取项目根目录
|
||
DATA_DIR = os.path.join(BASE_DIR, 'output') # 获取导出数据的文件根目录
|
||
os.makedirs(DATA_DIR, exist_ok=True) # 自动创建目录
|
||
|
||
# 配置文件路径
|
||
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.yaml')
|
||
# 加载配置并导出全局变量
|
||
config = load_config() # 模块导入时立即执行
|
||
MANAGEMENT_NODES = config["MANAGEMENT_NODES"]
|
||
SNAPSHOT_RETENTION_DAYS = config["SNAPSHOT_RETENTION_DAYS"]
|
||
EXCEL_OUTPUT_PATH = config["EXCEL_OUTPUT_PATH"]
|
||
YAML_OUTPUT_PATH = config["YAML_OUTPUT_PATH"]
|
||
DISABLE_SSL_VERIFY = config["DISABLE_SSL_VERIFY"]
|
||
# 调度配置
|
||
SCHEDULE_EXPORT = config["SCHEDULE_EXPORT"]
|
||
SCHEDULE_DELETE = config["SCHEDULE_DELETE"]
|
||
|
||
if __name__ == "__main__":
|
||
# 打印全局配置
|
||
print("\n【全局配置】")
|
||
print(f" 快照保留天数: {config['SNAPSHOT_RETENTION_DAYS']}")
|
||
print(f" Excel输出路径: {EXCEL_OUTPUT_PATH}")
|
||
|
||
# 打印管理节点
|
||
nodes = config['MANAGEMENT_NODES']
|
||
print(f"\n【管理节点】共 {len(nodes)} 个")
|
||
|
||
for i, node in enumerate(nodes, 1):
|
||
print(f"\n 节点[{i}]:")
|
||
print(f" 地址: {node.get('host')}")
|
||
print(f" 用户: {node.get('user')}")
|
||
print(f" 密码: {'*' * len(node.get('password', ''))}")
|
||
# print(f" 密码: {node.get('password', '')}") # 直接打印出密码 |