| 1 |
|
| 2 |
""" |
| 3 |
Script para ejecutar todos los playbooks de Ansible y generar un informe |
| 4 |
con los resultados de éxito y fallos. |
| 5 |
""" |
| 6 |
|
| 7 |
import os |
| 8 |
import re |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
from collections import defaultdict |
| 12 |
from datetime import datetime |
| 13 |
from pathlib import Path |
| 14 |
from typing import Dict, List, Tuple |
| 15 |
|
| 16 |
|
| 17 |
class PlaybookRunner: |
| 18 |
def __init__(self, playbooks_dir: str = "playbooks", logs_dir: str = "playbooks_logs"): |
| 19 |
self.playbooks_dir = Path(playbooks_dir) |
| 20 |
self.logs_dir = Path(logs_dir) |
| 21 |
self.results: List[Dict] = [] |
| 22 |
|
| 23 |
|
| 24 |
self.logs_dir.mkdir(exist_ok=True) |
| 25 |
|
| 26 |
s |
| 27 |
self.exit_codes = { |
| 28 |
0: "Éxito - El playbook se ejecutó correctamente", |
| 29 |
1: "Error general - Ocurrió un error durante la ejecución", |
| 30 |
2: "Tareas fallidas - Una o más tareas fallaron en uno o más hosts", |
| 31 |
3: "Hosts inalcanzables - Uno o más hosts no fueron alcanzables", |
| 32 |
4: "Error de sintaxis - Problemas con la sintaxis del playbook o opciones", |
| 33 |
5: "Mal uso - Uso incorrecto de ansible-playbook", |
| 34 |
99: "Error de usuario - Error causado por el usuario", |
| 35 |
250: "Error inesperado - Error inesperado en ansible-playbook" |
| 36 |
} |
| 37 |
|
| 38 |
def find_playbooks(self) -> List[Path]: |
| 39 |
"""Encuentra todos los archivos playbook (.yml y .yaml) en el directorio.""" |
| 40 |
playbooks = [] |
| 41 |
if not self.playbooks_dir.exists(): |
| 42 |
print(f"Error: El directorio {self.playbooks_dir} no existe") |
| 43 |
sys.exit(1) |
| 44 |
|
| 45 |
for ext in ['*.yml', '*.yaml']: |
| 46 |
playbooks.extend(self.playbooks_dir.glob(ext)) |
| 47 |
|
| 48 |
|
| 49 |
playbooks = [p for p in playbooks if p.is_file() and |
| 50 |
not p.name.endswith('.template')] |
| 51 |
|
| 52 |
return sorted(playbooks) |
| 53 |
|
| 54 |
def get_exit_code_meaning(self, exit_code: int) -> str: |
| 55 |
""" |
| 56 |
Obtiene el significado de un código de salida de ansible-playbook. |
| 57 |
|
| 58 |
Args: |
| 59 |
exit_code: Código de salida |
| 60 |
|
| 61 |
Returns: |
| 62 |
Descripción del código de salida |
| 63 |
""" |
| 64 |
return self.exit_codes.get(exit_code, f"Código desconocido: {exit_code}") |
| 65 |
|
| 66 |
def run_playbook(self, playbook_path: Path) -> Tuple[bool, str, str, int]: |
| 67 |
""" |
| 68 |
Ejecuta un playbook y retorna (éxito, stdout, stderr, exit_code). |
| 69 |
|
| 70 |
Args: |
| 71 |
playbook_path: Ruta al playbook |
| 72 |
|
| 73 |
Returns: |
| 74 |
Tupla con (éxito, stdout, stderr, exit_code) |
| 75 |
""" |
| 76 |
print(f"\n{'='*80}") |
| 77 |
print(f"Ejecutando: {playbook_path.name}") |
| 78 |
print(f"{'='*80}") |
| 79 |
|
| 80 |
try: |
| 81 |
|
| 82 |
result = subprocess.run( |
| 83 |
['ansible-playbook', str(playbook_path)], |
| 84 |
capture_output=True, |
| 85 |
text=True, |
| 86 |
timeout=600, |
| 87 |
cwd=self.playbooks_dir.parent |
| 88 |
) |
| 89 |
|
| 90 |
success = result.returncode == 0 |
| 91 |
stdout = result.stdout |
| 92 |
stderr = result.stderr |
| 93 |
exit_code = result.returncode |
| 94 |
|
| 95 |
if success: |
| 96 |
print(f"✓ {playbook_path.name} - ÉXITO") |
| 97 |
else: |
| 98 |
exit_meaning = self.get_exit_code_meaning(exit_code) |
| 99 |
print(f"✗ {playbook_path.name} - FALLÓ") |
| 100 |
print(f" Código de salida: {exit_code} - {exit_meaning}") |
| 101 |
uí |
| 102 |
print(f" Log completo se guardará en: {self.logs_dir}/") |
| 103 |
|
| 104 |
return success, stdout, stderr, exit_code |
| 105 |
|
| 106 |
except subprocess.TimeoutExpired: |
| 107 |
error_msg = f"Timeout: El playbook tardó más de 10 minutos en ejecutarse" |
| 108 |
print(f"✗ {playbook_path.name} - TIMEOUT") |
| 109 |
return False, "", error_msg, -1 |
| 110 |
|
| 111 |
except FileNotFoundError: |
| 112 |
error_msg = "Error: ansible-playbook no se encontró. ¿Está instalado Ansible?" |
| 113 |
print(f"✗ {playbook_path.name} - ERROR: {error_msg}") |
| 114 |
return False, "", error_msg, -1 |
| 115 |
|
| 116 |
except Exception as e: |
| 117 |
error_msg = f"Error inesperado: {str(e)}" |
| 118 |
print(f"✗ {playbook_path.name} - ERROR: {error_msg}") |
| 119 |
return False, "", error_msg, -1 |
| 120 |
|
| 121 |
def save_logs(self, playbook_name: str, stdout: str, stderr: str, exit_code: int) -> str: |
| 122 |
""" |
| 123 |
Guarda los logs completos de un playbook fallido en un archivo. |
| 124 |
|
| 125 |
Args: |
| 126 |
playbook_name: Nombre del playbook |
| 127 |
stdout: Salida estándar |
| 128 |
stderr: Salida de error |
| 129 |
exit_code: Código de salida |
| 130 |
|
| 131 |
Returns: |
| 132 |
Ruta al archivo de log guardado |
| 133 |
""" |
| 134 |
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') |
| 135 |
log_filename = f"{playbook_name}_{timestamp}.log" |
| 136 |
log_path = self.logs_dir / log_filename |
| 137 |
|
| 138 |
with open(log_path, 'w', encoding='utf-8') as f: |
| 139 |
f.write("=" * 80 + "\n") |
| 140 |
f.write(f"LOG DE EJECUCIÓN: {playbook_name}\n") |
| 141 |
f.write("=" * 80 + "\n") |
| 142 |
f.write(f"Fecha: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") |
| 143 |
f.write(f"Código de salida: {exit_code} - {self.get_exit_code_meaning(exit_code)}\n") |
| 144 |
f.write("\n" + "=" * 80 + "\n") |
| 145 |
f.write("SALIDA ESTÁNDAR (STDOUT)\n") |
| 146 |
f.write("=" * 80 + "\n") |
| 147 |
f.write(stdout) |
| 148 |
f.write("\n\n" + "=" * 80 + "\n") |
| 149 |
f.write("SALIDA DE ERROR (STDERR)\n") |
| 150 |
f.write("=" * 80 + "\n") |
| 151 |
f.write(stderr) |
| 152 |
f.write("\n" + "=" * 80 + "\n") |
| 153 |
|
| 154 |
return str(log_path) |
| 155 |
|
| 156 |
def extract_error_reason(self, stdout: str, stderr: str) -> str: |
| 157 |
""" |
| 158 |
Extrae la razón del fallo de la salida de ansible-playbook. |
| 159 |
|
| 160 |
Args: |
| 161 |
stdout: Salida estándar |
| 162 |
stderr: Salida de error |
| 163 |
|
| 164 |
Returns: |
| 165 |
Razón del fallo extraída |
| 166 |
""" |
| 167 |
|
| 168 |
output = stdout + "\n" + stderr |
| 169 |
|
| 170 |
s |
| 171 |
if "requires Python 3.10" in output or "Python 3.10 at minimum" in output: |
| 172 |
python_version = sys.version.split()[0] |
| 173 |
return f"❌ ERROR DE VERSIÓN DE PYTHON: Se requiere Python 3.10+, pero estás usando {python_version}. Actualiza Python o usa un entorno virtual con Python 3.10+." |
| 174 |
|
| 175 |
if "Could not find or access" in output: |
| 176 |
match = re.search(r"Could not find or access '([^']+)'", output) |
| 177 |
if match: |
| 178 |
return f"❌ ARCHIVO NO ENCONTRADO: No se pudo encontrar el archivo '{match.group(1)}'" |
| 179 |
|
| 180 |
if "authentication failed" in output.lower() or "unauthorized" in output.lower(): |
| 181 |
return "❌ ERROR DE AUTENTICACIÓN: Credenciales inválidas o expiradas. Verifica tu API key de Meraki." |
| 182 |
|
| 183 |
if "network_id" in output.lower() and ("required" in output.lower() or "missing" in output.lower()): |
| 184 |
return "❌ VARIABLE FALTANTE: Se requiere 'network_id' pero no está definida en el playbook." |
| 185 |
|
| 186 |
if "org_id" in output.lower() and ("required" in output.lower() or "missing" in output.lower()): |
| 187 |
return "❌ VARIABLE FALTANTE: Se requiere 'org_id' pero no está definida en el playbook." |
| 188 |
|
| 189 |
|
| 190 |
error_patterns = [ |
| 191 |
r'ERROR! (.+?)(?:\n|$)', |
| 192 |
r'fatal: (.+?)(?:\n|$)', |
| 193 |
r'failed: (.+?)(?:\n|$)', |
| 194 |
r'Error: (.+?)(?:\n|$)', |
| 195 |
r'Exception: (.+?)(?:\n|$)', |
| 196 |
] |
| 197 |
|
| 198 |
reasons = [] |
| 199 |
for pattern in error_patterns: |
| 200 |
matches = re.findall(pattern, output, re.IGNORECASE | re.MULTILINE) |
| 201 |
if matches: |
| 202 |
reasons.extend(matches[:2]) ón |
| 203 |
|
| 204 |
if reasons: |
| 205 |
|
| 206 |
reason = "; ".join(reasons[:3]) |
| 207 |
if len(reason) > 200: |
| 208 |
reason = reason[:200] + "..." |
| 209 |
return reason |
| 210 |
|
| 211 |
error |
| 212 |
lines = output.split('\n') |
| 213 |
error_lines = [line for line in lines if any(keyword in line.lower() |
| 214 |
for keyword in ['error', 'fatal', 'failed', 'exception'])] |
| 215 |
|
| 216 |
if error_lines: |
| 217 |
or |
| 218 |
last_errors = error_lines[-3:] |
| 219 |
reason = " | ".join(last_errors) |
| 220 |
if len(reason) > 200: |
| 221 |
reason = reason[:200] + "..." |
| 222 |
return reason |
| 223 |
|
| 224 |
ico |
| 225 |
if stderr: |
| 226 |
return stderr[:200] if len(stderr) <= 200 else stderr[:200] + "..." |
| 227 |
|
| 228 |
return "Razón desconocida (revisar logs)" |
| 229 |
|
| 230 |
def categorize_error(self, error_reason: str) -> str: |
| 231 |
""" |
| 232 |
Categoriza un error en un tipo específico. |
| 233 |
|
| 234 |
Args: |
| 235 |
error_reason: Razón del error |
| 236 |
|
| 237 |
Returns: |
| 238 |
Categoría del error |
| 239 |
""" |
| 240 |
if "VERSIÓN DE PYTHON" in error_reason: |
| 241 |
return "Versión de Python incompatible" |
| 242 |
elif "ARCHIVO NO ENCONTRADO" in error_reason: |
| 243 |
return "Archivo faltante" |
| 244 |
elif "AUTENTICACIÓN" in error_reason: |
| 245 |
return "Error de autenticación" |
| 246 |
elif "VARIABLE FALTANTE" in error_reason: |
| 247 |
return "Variable faltante" |
| 248 |
else: |
| 249 |
return "Otro error" |
| 250 |
|
| 251 |
def check_python_version(self) -> None: |
| 252 |
"""Verifica la versión de Python y muestra advertencias si es necesario.""" |
| 253 |
python_version = sys.version_info |
| 254 |
current_version = f"{python_version.major}.{python_version.minor}.{python_version.micro}" |
| 255 |
|
| 256 |
print(f"Python detectado: {current_version}") |
| 257 |
|
| 258 |
if python_version < (3, 10): |
| 259 |
print(f"\n⚠️ ADVERTENCIA: Estás usando Python {current_version}") |
| 260 |
print(" La librería Meraki SDK requiere Python 3.10 o superior.") |
| 261 |
print(" Muchos playbooks pueden fallar por esta razón.") |
| 262 |
print(" Considera actualizar Python o usar un entorno virtual con Python 3.10+") |
| 263 |
print("") |
| 264 |
|
| 265 |
def run_all(self) -> None: |
| 266 |
"""Ejecuta todos los playbooks y almacena los resultados.""" |
| 267 |
playbooks = self.find_playbooks() |
| 268 |
|
| 269 |
if not playbooks: |
| 270 |
print(f"No se encontraron playbooks en {self.playbooks_dir}") |
| 271 |
return |
| 272 |
|
| 273 |
print(f"\n{'='*80}") |
| 274 |
print(f"Encontrados {len(playbooks)} playbooks para ejecutar") |
| 275 |
print(f"Logs de playbooks fallidos se guardarán en: {self.logs_dir}/") |
| 276 |
print(f"{'='*80}\n") |
| 277 |
|
| 278 |
n |
| 279 |
self.check_python_version() |
| 280 |
|
| 281 |
for i, playbook in enumerate(playbooks, 1): |
| 282 |
print(f"\n[{i}/{len(playbooks)}] Procesando: {playbook.name}") |
| 283 |
|
| 284 |
success, stdout, stderr, exit_code = self.run_playbook(playbook) |
| 285 |
|
| 286 |
error_reason = "" |
| 287 |
exit_meaning = "" |
| 288 |
error_category = "" |
| 289 |
if not success: |
| 290 |
error_reason = self.extract_error_reason(stdout, stderr) |
| 291 |
exit_meaning = self.get_exit_code_meaning(exit_code) |
| 292 |
error_category = self.categorize_error(error_reason) |
| 293 |
|
| 294 |
ó |
| 295 |
log_file = None |
| 296 |
if not success: |
| 297 |
log_file = self.save_logs(playbook.name, stdout, stderr, exit_code) |
| 298 |
|
| 299 |
self.results.append({ |
| 300 |
'playbook': playbook.name, |
| 301 |
'path': str(playbook), |
| 302 |
'success': success, |
| 303 |
'exit_code': exit_code, |
| 304 |
'exit_meaning': exit_meaning, |
| 305 |
'error_reason': error_reason, |
| 306 |
'error_category': error_category, |
| 307 |
'stdout': stdout, |
| 308 |
'stderr': stderr, |
| 309 |
'log_file': log_file |
| 310 |
}) |
| 311 |
|
| 312 |
def generate_report(self, output_file: str = None) -> str: |
| 313 |
""" |
| 314 |
Genera un informe con los resultados de la ejecución. |
| 315 |
|
| 316 |
Args: |
| 317 |
output_file: Archivo donde guardar el informe (opcional) |
| 318 |
|
| 319 |
Returns: |
| 320 |
Contenido del informe |
| 321 |
""" |
| 322 |
total = len(self.results) |
| 323 |
successful = sum(1 for r in self.results if r['success']) |
| 324 |
failed = total - successful |
| 325 |
|
| 326 |
report_lines = [] |
| 327 |
report_lines.append("=" * 80) |
| 328 |
report_lines.append("INFORME DE EJECUCIÓN DE PLAYBOOKS") |
| 329 |
report_lines.append("=" * 80) |
| 330 |
report_lines.append(f"Fecha: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
| 331 |
report_lines.append(f"Total de playbooks: {total}") |
| 332 |
report_lines.append(f"Éxitos: {successful} ({successful/total*100:.1f}%)" if total > 0 else "Éxitos: 0") |
| 333 |
report_lines.append(f"Fallos: {failed} ({failed/total*100:.1f}%)" if total > 0 else "Fallos: 0") |
| 334 |
if failed > 0: |
| 335 |
report_lines.append(f"Logs de playbooks fallidos guardados en: {self.logs_dir}/") |
| 336 |
report_lines.append("") |
| 337 |
|
| 338 |
if successful > 0: |
| 339 |
report_lines.append("-" * 80) |
| 340 |
report_lines.append("PLAYBOOKS EXITOSOS") |
| 341 |
report_lines.append("-" * 80) |
| 342 |
for result in self.results: |
| 343 |
if result['success']: |
| 344 |
report_lines.append(f"✓ {result['playbook']}") |
| 345 |
report_lines.append("") |
| 346 |
|
| 347 |
if failed > 0: |
| 348 |
a |
| 349 |
errors_by_category = defaultdict(list) |
| 350 |
for result in self.results: |
| 351 |
if not result['success']: |
| 352 |
category = result.get('error_category', 'Otro error') |
| 353 |
errors_by_category[category].append(result) |
| 354 |
|
| 355 |
report_lines.append("-" * 80) |
| 356 |
report_lines.append("RESUMEN DE ERRORES POR CATEGORÍA") |
| 357 |
report_lines.append("-" * 80) |
| 358 |
for category, errors in sorted(errors_by_category.items(), key=lambda x: len(x[1]), reverse=True): |
| 359 |
report_lines.append(f"{category}: {len(errors)} playbook(s)") |
| 360 |
report_lines.append("") |
| 361 |
|
| 362 |
report_lines.append("-" * 80) |
| 363 |
report_lines.append("PLAYBOOKS FALLIDOS (DETALLES)") |
| 364 |
report_lines.append("-" * 80) |
| 365 |
|
| 366 |
s |
| 367 |
for category in sorted(errors_by_category.keys(), key=lambda x: len(errors_by_category[x]), reverse=True): |
| 368 |
if len(errors_by_category[category]) > 0: |
| 369 |
report_lines.append("") |
| 370 |
report_lines.append(f"📋 {category.upper()} ({len(errors_by_category[category])} playbook(s))") |
| 371 |
report_lines.append("-" * 80) |
| 372 |
|
| 373 |
for result in errors_by_category[category]: |
| 374 |
report_lines.append(f"✗ {result['playbook']}") |
| 375 |
if result['exit_code'] != -1: |
| 376 |
report_lines.append(f" Código de salida: {result['exit_code']} - {result['exit_meaning']}") |
| 377 |
if result['error_reason']: |
| 378 |
report_lines.append(f" Razón: {result['error_reason']}") |
| 379 |
if result.get('log_file'): |
| 380 |
report_lines.append(f" Log completo: {result['log_file']}") |
| 381 |
report_lines.append("") |
| 382 |
|
| 383 |
report_content = "\n".join(report_lines) |
| 384 |
|
| 385 |
if output_file: |
| 386 |
with open(output_file, 'w', encoding='utf-8') as f: |
| 387 |
f.write(report_content) |
| 388 |
print(f"\n✓ Informe guardado en: {output_file}") |
| 389 |
|
| 390 |
return report_content |
| 391 |
|
| 392 |
|
| 393 |
def main(): |
| 394 |
"""Función principal.""" |
| 395 |
import argparse |
| 396 |
|
| 397 |
parser = argparse.ArgumentParser( |
| 398 |
description='Ejecuta todos los playbooks de Ansible y genera un informe' |
| 399 |
) |
| 400 |
parser.add_argument( |
| 401 |
'--playbooks-dir', |
| 402 |
default='playbooks', |
| 403 |
help='Directorio donde están los playbooks (default: playbooks)' |
| 404 |
) |
| 405 |
parser.add_argument( |
| 406 |
'--output', |
| 407 |
'-o', |
| 408 |
default='playbooks_report.txt', |
| 409 |
help='Archivo de salida para el informe (default: playbooks_report.txt)' |
| 410 |
) |
| 411 |
parser.add_argument( |
| 412 |
'--no-report-file', |
| 413 |
action='store_true', |
| 414 |
help='No guardar el informe en un archivo, solo mostrarlo en consola' |
| 415 |
) |
| 416 |
parser.add_argument( |
| 417 |
'--logs-dir', |
| 418 |
default='playbooks_logs', |
| 419 |
help='Directorio donde guardar los logs de playbooks fallidos (default: playbooks_logs)' |
| 420 |
) |
| 421 |
|
| 422 |
args = parser.parse_args() |
| 423 |
|
| 424 |
runner = PlaybookRunner(playbooks_dir=args.playbooks_dir, logs_dir=args.logs_dir) |
| 425 |
|
| 426 |
try: |
| 427 |
runner.run_all() |
| 428 |
|
| 429 |
if args.no_report_file: |
| 430 |
report = runner.generate_report() |
| 431 |
print("\n" + report) |
| 432 |
else: |
| 433 |
report = runner.generate_report(output_file=args.output) |
| 434 |
print("\n" + report) |
| 435 |
|
| 436 |
o |
| 437 |
failed_count = sum(1 for r in runner.results if not r['success']) |
| 438 |
sys.exit(0 if failed_count == 0 else 1) |
| 439 |
|
| 440 |
except KeyboardInterrupt: |
| 441 |
print("\n\nEjecución interrumpida por el usuario") |
| 442 |
sys.exit(130) |
| 443 |
except Exception as e: |
| 444 |
print(f"\nError fatal: {e}") |
| 445 |
import traceback |
| 446 |
traceback.print_exc() |
| 447 |
sys.exit(1) |
| 448 |
|
| 449 |
|
| 450 |
if __name__ == "__main__": |
| 451 |
main() |
| 452 |
|