الفصل 12.3 - الأتمتة الكاملة
أهداف التعلم
في نهاية هذا الفصل، ستكون قادرًا على:
- إنشاء أنظمة أتمتة كاملة
- دمج cron مع البرامج النصية المتقدمة
- تنفيذ سير العمل الآلي
- إدارة الأخطاء وإعادة المحاولة
- إنشاء أنظمة إشعارات
- توثيق الأتمتة
بنية الأتمتة
المكونات
العناصر:
- الجدولة (cron/systemd timers)
- البرامج النصية القابلة للتنفيذ
- التسجيل
- الإشعارات
- المراقبة
إطار الأتمتة
الهيكل الأساسي
#!/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 "$@"
سير العمل الآلي
النسخ الاحتياطي الآلي
#!/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é"
المراقبة الآلية
#!/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 "ALERTE: $metric à ${value}% (seuil: ${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 "Alerte $metric" "$metric dépassé"
done
إدارة الأخطاء وإعادة المحاولة
وظيفة إعادة المحاولة
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
إدارة الأخطاء المتقدمة
#!/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
# ...
نظام الإشعارات
الإشعارات متعددة القنوات
#!/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"
توثيق الأتمتة
Runbook الأتمتة
# Runbook: Système d'Automatisation
## Vue d'Ensemble
Système automatisé pour maintenance et monitoring
## Composants
- Cron: Planification tâches
- Scripts: /usr/local/bin/automation/
- Logs: /var/log/automation/
- Notifications: Email + Slack
## Tâches Planifiées
- Backup: Quotidien 2h
- Monitoring: Toutes les 5 minutes
- Nettoyage: Hebdomadaire dimanche 3h
- Rapports: Quotidien 8h
## Troubleshooting
- Vérifier logs: /var/log/automation/
- Vérifier cron: grep CRON /var/log/syslog
- Vérifier locks: /var/run/automation/
توثيق البرامج النصية
#!/bin/bash
# Script: mon-automation.sh
# Auteur: Admin
# Date: 2024-12
# Description: Automatisation complète maintenance
# Usage: Exécuté par cron
# Dependencies: mail, curl
# Logs: /var/log/automation/mon-automation.log
مثال كامل
نظام الأتمتة في الإنتاج
#!/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 الإنتاج
# /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
ملخص
في هذا الفصل، تعلمت:
البنية: مكونات نظام الأتمتة
الإطار: هيكل قابل لإعادة الاستخدام، وظائف مساعدة
سير العمل: النسخ الاحتياطي، المراقبة، المهام المعقدة
الأخطاء: إعادة المحاولة، الإدارة المتقدمة، التسجيل
الإشعارات: متعددة القنوات، البريد الإلكتروني، Slack
التوثيق: Runbooks، تعليقات البرامج النصية
الممارسة: نظام إنتاج كامل
نهاية الدورة
تهانينا! لقد أكملت دورة Linux الكاملة مع أتمتة cron المتقدمة.
الخطوات التالية:
- الممارسة على الخوادم الحقيقية
- تنفيذ الأتمتة الخاصة بك
- الاستمرار في التعلم والاستكشاف
الفصل تم إنشاؤه في: ديسمبر 2024