Capítulo 12.3 - Automatización Completa
Objetivos de Aprendizaje
Al final de este capítulo, usted será capaz de:
- Crear sistemas de automatización completos
- Integrar cron con scripts avanzados
- Implementar flujos de trabajo automatizados
- Gestionar errores y reintentos
- Crear sistemas de notificación
- Documentar la automatización
Arquitectura de Automatización
Componentes
Elementos:
- Planificación (cron/systemd timers)
- Scripts ejecutables
- Logging
- Notificaciones
- Monitoreo
Framework de Automatización
Estructura Básica
#!/bin/bash
# Framework automatisation
set -euo pipefail
# Configuration
SCRIPT_NAME="mon-automation"
LOG_DIR="/var/log/automation"
LOCK_DIR="/var/run/automation"
NOTIFY_EMAIL="admin@example.com"
# Fonctions utilitaires
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_DIR/$SCRIPT_NAME.log"
}
notify() {
local subject="$1"
local message="$2"
echo "$message" | mail -s "$subject" "$NOTIFY_EMAIL"
}
cleanup() {
rm -f "$LOCK_DIR/$SCRIPT_NAME.lock"
log "Nettoyage terminé"
}
# Trap pour nettoyage
trap cleanup EXIT
# Lock file
LOCK_FILE="$LOCK_DIR/$SCRIPT_NAME.lock"
if [ -f "$LOCK_FILE" ]; then
log "Script déjà en cours d'exécution"
exit 1
fi
touch "$LOCK_FILE"
# Code principal
main() {
log "Début automatisation"
# Tâches...
task1
task2
task3
log "Fin automatisation"
}
main "$@"
Workflows Automatizados
Backup Automatizado
#!/bin/bash
# Backup automatisé complet
set -euo pipefail
BACKUP_DIR="/backup"
SOURCES=("/data" "/etc" "/home")
RETENTION_DAYS=7
LOG="/var/log/backup.log"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG"
}
backup_source() {
local source="$1"
local dest="$BACKUP_DIR/$(basename $source)-$(date +%Y%m%d).tar.gz"
log "Backup: $source -> $dest"
tar -czf "$dest" "$source" || {
log "ERREUR: Échec backup $source"
return 1
}
log "Succès: $dest créé ($(du -h $dest | cut -f1))"
}
# Backup chaque source
for source in "${SOURCES[@]}"; do
backup_source "$source"
done
# Nettoyage anciens backups
log "Nettoyage backups > $RETENTION_DAYS jours"
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
log "Backup terminé"
Monitoreo Automatizado
#!/bin/bash
# Monitoring automatisé
THRESHOLDS=(
"CPU:80"
"MEM:85"
"DISK:90"
)
check_threshold() {
local metric="$1"
local threshold="$2"
local value
case "$metric" in
CPU)
value=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | sed 's/%us,//')
;;
MEM)
value=$(free | grep Mem | awk '{printf "%.0f", $3/$2 * 100}')
;;
DISK)
value=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')
;;
esac
if [ "$value" -gt "$threshold" ]; then
echo "ALERTA: $metric a ${value}% (umbral: ${threshold}%)"
return 1
fi
return 0
}
# Vérifier tous les seuils
for threshold in "${THRESHOLDS[@]}"; do
metric=$(echo $threshold | cut -d: -f1)
value=$(echo $threshold | cut -d: -f2)
check_threshold "$metric" "$value" || notify "Alerta $metric" "$metric superado"
done
Gestión de Errores y Retry
Función Retry
retry() {
local max_attempts="$1"
local delay="$2"
shift 2
local command="$@"
local attempt=1
while [ $attempt -le $max_attempts ]; do
if $command; then
return 0
fi
if [ $attempt -lt $max_attempts ]; then
log "Tentative $attempt/$max_attempts échouée, retry dans ${delay}s"
sleep "$delay"
fi
attempt=$((attempt + 1))
done
log "ERREUR: Toutes les tentatives échouées"
return 1
}
# Utilisation
retry 3 5 wget http://example.com/file.txt
Gestión Avanzada de Errores
#!/bin/bash
# Gestion erreurs complète
ERROR_LOG="/var/log/automation-errors.log"
handle_error() {
local line="$1"
local command="$2"
local exit_code="$3"
echo "[$(date)] ERREUR ligne $line: $command (code: $exit_code)" >> "$ERROR_LOG"
# Notification
echo "Erreur dans automatisation ligne $line" | \
mail -s "Erreur Automatisation" admin@example.com
# Logging
log "ERREUR: $command (ligne $line, code $exit_code)"
}
# Trap erreurs
trap 'handle_error $LINENO "$BASH_COMMAND" $?' ERR
# Code avec gestion erreurs
set -e
# ...
Sistema de Notificación
Notificaciones Multicanal
#!/bin/bash
# Système notification
notify() {
local level="$1" # info, warning, error
local message="$2"
# Email
echo "$message" | mail -s "[$level] Automatisation" admin@example.com
# Slack (si configuré)
if [ -n "$SLACK_WEBHOOK" ]; then
local color="good"
[ "$level" = "error" ] && color="danger"
[ "$level" = "warning" ] && color="warning"
curl -X POST -H 'Content-type: application/json' \
--data "{\"attachments\":[{\"color\":\"$color\",\"text\":\"$message\"}]}" \
"$SLACK_WEBHOOK" 2>/dev/null || true
fi
# Log
log "[$level] $message"
}
# Utilisation
notify "info" "Tâche démarrée"
notify "warning" "Attention: seuil proche"
notify "error" "ERREUR: Échec tâche"
Documentación de Automatización
Runbook de Automatización
# Runbook: Sistema de Automatización
## Visión General
Sistema automatizado para mantenimiento y monitoreo
## Componentes
- Cron: Planificación de tareas
- Scripts: /usr/local/bin/automation/
- Logs: /var/log/automation/
- Notificaciones: Email + Slack
## Tareas Programadas
- Backup: Diario 2h
- Monitoreo: Cada 5 minutos
- Limpieza: Semanal domingo 3h
- Reportes: Diario 8h
## Troubleshooting
- Verificar logs: /var/log/automation/
- Verificar cron: grep CRON /var/log/syslog
- Verificar locks: /var/run/automation/
Documentación de Scripts
#!/bin/bash
# Script: mon-automation.sh
# Autor: Admin
# Fecha: 2024-12
# Descripción: Automatización completa mantenimiento
# Uso: Ejecutado por cron
# Dependencias: mail, curl
# Logs: /var/log/automation/mon-automation.log
Ejemplo Completo
Sistema de Automatización de Producción
#!/bin/bash
# /usr/local/bin/automation-production.sh
# Système automatisation production
set -euo pipefail
# Configuration
SCRIPT_DIR="/usr/local/bin/automation"
LOG_DIR="/var/log/automation"
LOCK_DIR="/var/run/automation"
NOTIFY_EMAIL="admin@example.com"
# Créer répertoires
mkdir -p "$LOG_DIR" "$LOCK_DIR"
# Lock
LOCK="$LOCK_DIR/production.lock"
[ -f "$LOCK" ] && exit 1
touch "$LOCK"
trap "rm -f $LOCK" EXIT
# Logging
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_DIR/production.log"
}
# Notification
notify() {
echo "$*" | mail -s "Automatisation Production" "$NOTIFY_EMAIL"
}
# Tâches
log "=== Début automatisation ==="
# 1. Monitoring
log "Monitoring..."
"$SCRIPT_DIR/monitor.sh" || notify "Alerte: Monitoring échoué"
# 2. Backup
log "Backup..."
"$SCRIPT_DIR/backup.sh" || notify "Alerte: Backup échoué"
# 3. Nettoyage
log "Nettoyage..."
"$SCRIPT_DIR/cleanup.sh"
# 4. Rapport
log "Génération rapport..."
"$SCRIPT_DIR/report.sh"
log "=== Fin automatisation ==="
notify "Automatisation production terminée avec succès"
Crontab de Producción
# /etc/cron.d/production-automation
# Monitoring toutes les 5 minutes
*/5 * * * * root /usr/local/bin/automation/monitor.sh
# Backup quotidien 2h
0 2 * * * root /usr/local/bin/automation/backup.sh
# Nettoyage hebdomadaire
0 3 * * 0 root /usr/local/bin/automation/cleanup.sh
# Rapport quotidien
0 8 * * * root /usr/local/bin/automation/report.sh
# Automatisation complète quotidienne
0 1 * * * root /usr/local/bin/automation-production.sh
Resumen
En este capítulo, usted ha aprendido:
Arquitectura: Componentes del sistema de automatización
Framework: Estructura reutilizable, funciones utilitarias
Workflows: Backup, monitoreo, tareas complejas
Errores: Retry, gestión avanzada, logging
Notificaciones: Multicanal, email, Slack
Documentación: Runbooks, comentarios en scripts
Práctica: Sistema de producción completo
Fin del Curso
¡Felicidades! Usted ha completado la formación Linux completa con automatización cron avanzada.
Próximos pasos:
- Practicar en servidores reales
- Implementar sus propias automatizaciones
- Continuar aprendiendo y explorando
Capítulo creado el: Diciembre 2024