Get Vms Snapshots and Export Excel has completed.
This commit is contained in:
35
config/config.yaml
Normal file
35
config/config.yaml
Normal file
@@ -0,0 +1,35 @@
|
||||
# 管理节点配置(包含vCenter和ESXi)
|
||||
management_nodes:
|
||||
# vCenter节点
|
||||
- type: vcenter # 标记类型为vcenter
|
||||
name: vc1 # 节点名称(用于日志)
|
||||
host: 192.168.40.134 # 地址
|
||||
user: administrator@lan.com
|
||||
password: Root@2025
|
||||
max_delete_concurrent: 4 # 该节点最大并发删除数
|
||||
|
||||
# ESXi节点(未接入 vCenter 的 Esxi 主机)
|
||||
- type: esxi # 标记类型为esxi
|
||||
name: esxi1
|
||||
host: 192.168.40.133
|
||||
user: root # ESXi默认用root
|
||||
password: Root@2025
|
||||
max_delete_concurrent: 2 # ESXi性能较弱,并发数可设小些
|
||||
|
||||
# 另一个ESXi节点
|
||||
- type: esxi
|
||||
name: esxi2
|
||||
host: esxi2.example.com
|
||||
user: root
|
||||
password: esxi2_password
|
||||
max_delete_concurrent: 2
|
||||
|
||||
# 全局策略配置
|
||||
global:
|
||||
snapshot_retention_days: 15
|
||||
excel_output_path: ./vm_snapshots_report.xlsx
|
||||
# excel_output_path: /tmp/vm_snapshots_report.xlsx
|
||||
# log_file_path: /var/log/vm_snapshot_cleanup.log
|
||||
log_file_path: ./vm_snapshot_cleanup.log
|
||||
# ESXi连接特殊配置(禁用SSL验证,ESXi默认自签证书)
|
||||
disable_ssl_verify: true
|
||||
@@ -1,33 +1,88 @@
|
||||
import yaml
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from dotenv import load_dotenv
|
||||
# from utils.logger import logger
|
||||
|
||||
# 加载.env文件
|
||||
load_dotenv()
|
||||
# 配置文件路径
|
||||
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.yaml')
|
||||
|
||||
# ========== 基础配置 ==========
|
||||
# vCenter配置
|
||||
VCENTER_HOSTS = os.getenv('VCENTER_HOSTS', '').split(',')
|
||||
VCENTER_USER = os.getenv('VCENTER_USER', '')
|
||||
VCENTER_PASSWORD = os.getenv('VCENTER_PASSWORD', '')
|
||||
|
||||
# 快照策略配置
|
||||
SNAPSHOT_RETENTION_DAYS = int(os.getenv('SNAPSHOT_RETENTION_DAYS', 15))
|
||||
MAX_DELETE_CONCURRENT = int(os.getenv('MAX_DELETE_CONCURRENT', 4))
|
||||
def load_config():
|
||||
"""加载YAML配置,区分vCenter和ESXi"""
|
||||
try:
|
||||
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
|
||||
raw_config = yaml.safe_load(f)
|
||||
|
||||
# 输出路径配置
|
||||
EXCEL_OUTPUT_PATH = os.getenv('EXCEL_OUTPUT_PATH', '/tmp/vm_snapshots_report.xlsx')
|
||||
LOG_FILE_PATH = os.getenv('LOG_FILE_PATH', '/var/log/vm_snapshot_cleanup.log')
|
||||
# 全局配置
|
||||
global_config = raw_config.get('global', {})
|
||||
config = {
|
||||
# vCenter/ESXi节点列表
|
||||
"MANAGEMENT_NODES": raw_config.get('management_nodes', []),
|
||||
# vCenter/ESXi节点列表
|
||||
"SNAPSHOT_RETENTION_DAYS": int(global_config.get('snapshot_retention_days', 15)),
|
||||
"EXCEL_OUTPUT_PATH": global_config.get('excel_output_path', '/tmp/vm_snapshots_report.xlsx'),
|
||||
"LOG_FILE_PATH": global_config.get('log_file_path', '/var/log/vm_snapshot_cleanup.log'),
|
||||
"DISABLE_SSL_VERIFY": global_config.get('disable_ssl_verify', True),
|
||||
# 算出的过期时间点
|
||||
"EXPIRE_DATE": datetime.now() - timedelta(days=int(global_config.get('snapshot_retention_days', 15)))
|
||||
}
|
||||
|
||||
# 计算快照过期时间(全局变量)
|
||||
EXPIRE_DATE = datetime.now() - timedelta(days=SNAPSHOT_RETENTION_DAYS)
|
||||
# 验证配置
|
||||
if not config["MANAGEMENT_NODES"]:
|
||||
raise ValueError("未配置任何管理节点(vCenter/ESXi)")
|
||||
|
||||
# 验证必要配置
|
||||
# 检查每个节点的必填字段
|
||||
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
|
||||
|
||||
|
||||
# 加载配置并导出全局变量
|
||||
config = load_config() # 模块导入时立即执行
|
||||
MANAGEMENT_NODES = config["MANAGEMENT_NODES"]
|
||||
SNAPSHOT_RETENTION_DAYS = config["SNAPSHOT_RETENTION_DAYS"]
|
||||
EXCEL_OUTPUT_PATH = config["EXCEL_OUTPUT_PATH"]
|
||||
LOG_FILE_PATH = config["LOG_FILE_PATH"]
|
||||
DISABLE_SSL_VERIFY = config["DISABLE_SSL_VERIFY"]
|
||||
EXPIRE_DATE = config["EXPIRE_DATE"]
|
||||
|
||||
|
||||
# 验证配置函数
|
||||
def validate_config():
|
||||
"""验证配置是否完整"""
|
||||
required = [
|
||||
VCENTER_HOSTS, VCENTER_USER, VCENTER_PASSWORD,
|
||||
SNAPSHOT_RETENTION_DAYS, MAX_DELETE_CONCURRENT
|
||||
]
|
||||
if not all(required) or '' in VCENTER_HOSTS:
|
||||
raise ValueError("配置不完整,请检查.env文件中的vCenter信息和策略配置")
|
||||
pass # 加载时已验证,此处留空
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 打印全局配置
|
||||
print("\n【全局配置】")
|
||||
print(f" 快照保留天数: {config['SNAPSHOT_RETENTION_DAYS']}")
|
||||
print(f" 过期日期: {config['EXPIRE_DATE']}")
|
||||
print(f" Excel输出路径: {config['EXCEL_OUTPUT_PATH']}")
|
||||
print(f" 日志文件路径: {config['LOG_FILE_PATH']}")
|
||||
print(f" 禁用SSL验证: {config['DISABLE_SSL_VERIFY']}")
|
||||
|
||||
# 打印管理节点
|
||||
nodes = config['MANAGEMENT_NODES']
|
||||
print(f"\n【管理节点】共 {len(nodes)} 个")
|
||||
|
||||
for i, node in enumerate(nodes, 1):
|
||||
print(f"\n 节点[{i}]:")
|
||||
print(f" 类型: {node.get('type')}")
|
||||
print(f" 名称: {node.get('name')}")
|
||||
print(f" 地址: {node.get('host')}")
|
||||
print(f" 用户: {node.get('user')}")
|
||||
print(f" 密码: {'*' * len(node.get('password', ''))}")
|
||||
# print(f" 密码: {node.get('password', '')}") # 直接打印出密码
|
||||
print(f" 最大并发删除: {node.get('max_delete_concurrent')}")
|
||||
Reference in New Issue
Block a user