# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 1: INTRODUCTION ET CONCEPTS FONDAMENTAUX
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════

# Ce guide explore TOUTES les fonctionnalités de VMware de manière exhaustive
# Chaque concept est expliqué avec:
# - POURQUOI: La raison d'être de cette fonctionnalité
# - QUAND: Les cas d'usage appropriés
# - COMMENT: L'implémentation pratique avec exemples
# - Analogies pour faciliter la compréhension
# - Erreurs courantes et comment les éviter


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 1: QU'EST-CE QUE LA VIRTUALISATION?
# ═══════════════════════════════════════════════════════════════════


# ═══ 1.1 POURQUOI LA VIRTUALISATION EXISTE? ═══

# PROBLÈME AVANT LA VIRTUALISATION:
# ═════════════════════════════════

# Imaginez une entreprise avec ces besoins:
# - Serveur Web (Linux Apache)
# - Serveur Base de données (Linux MySQL)
# - Serveur Email (Linux Postfix)
# - Serveur DNS (Linux BIND)
# - Serveur Fichiers (Windows Server)

# Solution traditionnelle (AVANT virtualisation):
# ──────────────────────────────────────────────
# 5 serveurs physiques différents!
# 
# Serveur 1: [Linux Apache]     - CPU: 10% utilisé, RAM: 20% utilisée
# Serveur 2: [Linux MySQL]      - CPU: 25% utilisé, RAM: 40% utilisée
# Serveur 3: [Linux Postfix]    - CPU: 5% utilisé, RAM: 15% utilisée
# Serveur 4: [Linux BIND]       - CPU: 3% utilisé, RAM: 10% utilisée
# Serveur 5: [Windows Server]   - CPU: 15% utilisé, RAM: 30% utilisée
# 
# TOTAL: 5 machines physiques
# Utilisation moyenne: 11.6% CPU, 23% RAM
# 
# PROBLÈMES:
# [X] Gaspillage de ressources (88% CPU inutilisé!)
# [X] Coût énorme (5 serveurs × 2000€ = 10,000€)
# [X] Espace physique (5 racks)
# [X] Consommation électrique (5 × 500W = 2500W)
# [X] Refroidissement (climatisation pour 5 serveurs)
# [X] Maintenance complexe (5 machines à gérer)
# [X] Pas de flexibilité (serveur = 1 seule tâche)
# [X] Temps installation long (commander, installer, configurer)


# SOLUTION AVEC VIRTUALISATION:
# ════════════════════════════

# 1 SEUL serveur physique puissant avec 5 machines virtuelles!
# 
# ┌──────────────────────────────────────────────────────────┐
# │         SERVEUR PHYSIQUE (Host)                          │
# │  CPU: 32 cœurs  |  RAM: 128 GB  |  Disque: 4 TB         │
# │                                                           │
# │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
# │  │   VM 1      │  │   VM 2      │  │   VM 3      │     │
# │  │Linux Apache │  │Linux MySQL  │  │Linux Postfix│     │
# │  │4 CPU, 8GB   │  │8 CPU, 16GB  │  │2 CPU, 4GB   │     │
# │  └─────────────┘  └─────────────┘  └─────────────┘     │
# │                                                           │
# │  ┌─────────────┐  ┌─────────────┐                       │
# │  │   VM 4      │  │   VM 5      │                       │
# │  │Linux BIND   │  │Windows Srv  │                       │
# │  │2 CPU, 4GB   │  │8 CPU, 16GB  │                       │
# │  └─────────────┘  └─────────────┘                       │
# │                                                           │
# │              VMware ESXi (Hyperviseur)                   │
# └──────────────────────────────────────────────────────────┘
# 
# AVANTAGES:
# [OK] 1 seule machine physique (économie 8000€)
# [OK] Utilisation optimale ressources (70-80% CPU/RAM)
# [OK] 1 seul rack (économie espace)
# [OK] Consommation réduite (1 × 800W = 2500W -> 800W)
# [OK] Maintenance simplifiée (1 machine au lieu de 5)
# [OK] Flexibilité totale (créer/supprimer VMs en minutes)
# [OK] Isolation (problème VM1 n'affecte pas VM2)
# [OK] Snapshots (sauvegardes instantanées)
# [OK] Migration à chaud (déplacer VM sans arrêt)


# ANALOGIE: Immeuble vs Maisons individuelles
# ══════════════════════════════════════════════

# Sans virtualisation (Maisons individuelles):
# ────────────────────────────────────────────
# Famille 1 -> Maison 1 (4 chambres, seulement 1 utilisée)
# Famille 2 -> Maison 2 (4 chambres, seulement 2 utilisées)
# Famille 3 -> Maison 3 (4 chambres, seulement 1 utilisée)
# 
# Problèmes:
# - Gaspillage espace (chambres vides)
# - Coût construction 3 maisons
# - 3 toits, 3 chauffages, 3 jardins
# - Entretien 3 maisons

# Avec virtualisation (Immeuble):
# ───────────────────────────────
# 1 Immeuble avec 3 appartements
# Famille 1 -> Appart. 2 chambres (ce dont elle a besoin)
# Famille 2 -> Appart. 3 chambres
# Famille 3 -> Appart. 2 chambres
# 
# Avantages:
# - Espace optimisé (chacun a ce qu'il faut)
# - Coût construction réduit
# - 1 toit, 1 chauffage central, 1 terrain
# - Entretien centralisé
# 
# Immeuble = Serveur physique
# Appartements = Machines virtuelles
# Familles = Systèmes d'exploitation


# ═══ 1.2 QU'EST-CE QUE VMWARE? ═══

# DÉFINITION SIMPLE:
# ═════════════════

# VMware = Logiciel qui permet de créer des "ordinateurs virtuels"
# dans un ordinateur physique réel.
# 
# C'est comme avoir plusieurs ordinateurs dans un seul!


# HISTOIRE VMWARE:
# ═══════════════

# 1998: Création de VMware, Inc. par Diane Greene et Mendel Rosenblum
# 1999: VMware Workstation 1.0 (premier produit)
# 2001: VMware ESX Server (pour datacenters)
# 2004: Introduction de VMotion (migration à chaud)
# 2009: VMware vSphere (suite complète virtualisation)
# 2021: Rachat par Broadcom (58 milliards $)
# 
# Aujourd'hui: Leader mondial virtualisation
# - 500,000+ clients
# - 80% Fortune 500 utilisent VMware
# - Concurrents: Microsoft Hyper-V, Citrix XenServer, KVM


# PRODUITS VMWARE PRINCIPAUX:
# ═══════════════════════════

# 1. VMware Workstation Pro/Player (DESKTOP)
# ──────────────────────────────────────────
# Pour: Développeurs, étudiants, testeurs
# Usage: Créer VMs sur PC Windows/Linux
# Coût: Workstation Pro ~300€, Player GRATUIT
# 
# Fonctionnalités:
# • Créer VMs Windows, Linux, macOS
# • Snapshots (sauvegardes état VM)
# • Clone VMs
# • Réseau virtuel (NAT, Bridge, Host-Only)
# • Partage fichiers Host<->Guest
# • USB passthrough
# • Support DirectX/OpenGL (3D)

# 2. VMware Fusion (MAC)
# ──────────────────────
# Équivalent Workstation pour macOS
# Permet: Exécuter Windows/Linux sur Mac


# 3. VMware ESXi (SERVEUR BARE-METAL)
# ────────────────────────────────────
# Pour: Entreprises, datacenters, production
# Type: Hyperviseur de type 1 (bare-metal)
# Installation: Directement sur hardware (pas d'OS hôte)
# Coût: Version gratuite limitée, payant pour features avancées
# 
# Fonctionnalités:
# • Haute disponibilité (HA)
# • vMotion (migration à chaud)
# • Distributed Resource Scheduler (DRS)
# • Fault Tolerance
# • vSAN (stockage distribué)
# • Support 100s de VMs par serveur

# 4. VMware vSphere/vCenter (GESTION CENTRALISÉE)
# ───────────────────────────────────────────────
# Pour: Gérer plusieurs serveurs ESXi
# Interface: Web-based (HTML5)
# Fonctionnalités:
# • Dashboard centralised
# • Gestion pools de ressources
# • Automatisation (DRS, HA)
# • Monitoring performances
# • Gestion stockage centralisé


# 5. VMware Horizon (VDI - Virtual Desktop Infrastructure)
# ────────────────────────────────────────────────────────
# Pour: Bureaux virtuels (accès depuis anywhere)
# Usage: Entreprises avec télétravail
# Exemple: User se connecte depuis home, accède bureau Windows


# QUEL VMWARE POUR VOUS?
# ═════════════════════

# [OK] ÉTUDIANT / APPRENTISSAGE:
# -> VMware Workstation Player (GRATUIT)
# -> VMware Workstation Pro (si budget école)

# [OK] DÉVELOPPEUR:
# -> VMware Workstation Pro
# -> Tester applications sur différents OS

# [OK] ADMINISTRATEUR SYSTÈME (PME):
# -> VMware ESXi (version gratuite)
# -> 1-5 serveurs physiques

# [OK] ADMINISTRATEUR SYSTÈME (Grande entreprise):
# -> VMware vSphere + vCenter
# -> Cluster de serveurs ESXi

# [OK] UTILISATEUR MAC:
# -> VMware Fusion


# ═══ 1.3 TYPES D'HYPERVISEURS ═══

# HYPERVISEUR = Logiciel qui permet virtualisation
# 2 types principaux:


# TYPE 1: BARE-METAL (Metal nu)
# ═════════════════════════════

# Installation: DIRECTEMENT sur hardware physique
# Pas d'OS hôte intermédiaire
# 
# ┌────────────────────────────────────┐
# │          VM1    VM2    VM3         │ <- VMs
# ├────────────────────────────────────┤
# │       HYPERVISEUR (ESXi)           │ <- Hyperviseur Type 1
# ├────────────────────────────────────┤
# │      MATÉRIEL PHYSIQUE             │ <- Serveur
# │  CPU | RAM | Disque | Réseau       │
# └────────────────────────────────────┘
# 
# Exemples:
# • VMware ESXi (leader)
# • Microsoft Hyper-V Server
# • Citrix XenServer
# • KVM (Linux)
# 
# Avantages:
# [OK] Performances maximales (accès direct hardware)
# [OK] Sécurité renforcée (pas d'OS à compromettre)
# [OK] Stabilité (moins de couches logicielles)
# [OK] Optimisé pour production
# 
# Inconvénients:
# [X] Dédié uniquement virtualisation
# [X] Setup plus complexe
# [X] Nécessite serveur dédié
# 
# Usage: PRODUCTION, Datacenters, Entreprises


# TYPE 2: HOSTED (Hébergé)
# ═══════════════════════

# Installation: SUR un OS existant (Windows, Linux, macOS)
# 
# ┌────────────────────────────────────┐
# │          VM1    VM2    VM3         │ <- VMs
# ├────────────────────────────────────┤
# │   HYPERVISEUR (Workstation)        │ <- Hyperviseur Type 2
# ├────────────────────────────────────┤
# │    OS HÔTE (Windows/Linux/macOS)   │ <- OS existant
# ├────────────────────────────────────┤
# │      MATÉRIEL PHYSIQUE             │
# │  CPU | RAM | Disque | Réseau       │
# └────────────────────────────────────┘
# 
# Exemples:
# • VMware Workstation Pro/Player
# • VMware Fusion
# • Oracle VirtualBox
# • Parallels Desktop
# 
# Avantages:
# [OK] Facile à installer (comme application normale)
# [OK] Cohabite avec OS hôte
# [OK] Partage ressources avec hôte
# [OK] Idéal développement/test
# 
# Inconvénients:
# [X] Performances réduites (couche OS hôte)
# [X] Moins sécurisé (vulnérabilités OS hôte)
# [X] Overhead mémoire/CPU
# 
# Usage: DÉVELOPPEMENT, Tests, Formation, Démonstrations


# COMPARAISON:
# ═══════════

# ┌─────────────────┬──────────────┬──────────────┐
# │ Critère         │ Type 1       │ Type 2       │
# ├─────────────────┼──────────────┼──────────────┤
# │ Performances    │ *****  │ ***      │
# │ Sécurité        │ *****  │ ***      │
# │ Facilité setup  │ **         │ ***** │
# │ Coût            │ €€€          │ € ou Gratuit │
# │ Production      │ [OK] OUI        │ [X] NON        │
# │ Développement   │ Overkill     │ [OK] PARFAIT    │
# └─────────────────┴──────────────┴──────────────┘


# ═══ 1.4 TERMINOLOGIE ESSENTIELLE ═══

# VOCABULAIRE À MAÎTRISER:
# ═══════════════════════

# HOST (Hôte):
# ───────────
# Machine physique qui exécute l'hyperviseur
# C'est votre serveur ou PC réel
# 
# Exemple: Votre PC avec CPU Intel i7, 16GB RAM, 512GB SSD
# -> C'est le HOST

# GUEST (Invité):
# ──────────────
# Machine virtuelle qui s'exécute sur le host
# Système d'exploitation virtualisé
# 
# Exemple: VM Ubuntu installée dans VMware Workstation
# -> C'est un GUEST

# HYPERVISEUR (Hypervisor):
# ────────────────────────
# Logiciel qui crée et gère les VMs
# Alloue ressources Host vers Guests
# 
# Exemples: VMware ESXi, VMware Workstation, VirtualBox

# VM (Virtual Machine - Machine Virtuelle):
# ─────────────────────────────────────────
# Ordinateur logiciel qui fonctionne comme ordinateur physique
# A son propre CPU virtuel, RAM, disque, réseau
# 
# Fichiers d'une VM VMware:
# • .vmx (configuration VM)
# • .vmdk (disque virtuel)
# • .nvram (BIOS settings)
# • .vmem (RAM sauvegardée)

# SNAPSHOT:
# ────────
# "Photo" de l'état complet d'une VM à un instant T
# Permet revenir en arrière si problème
# 
# Exemple:
# 1. Prendre snapshot "Avant mise à jour"
# 2. Installer updates Windows
# 3. Problème? -> Restaurer snapshot
# 4. VM revient exactement état "Avant mise à jour"

# CLONE:
# ─────
# Copie complète d'une VM
# 2 types:
# • Full Clone: Copie indépendante (utilise propre disque)
# • Linked Clone: Dépend VM parent (économise espace)

# TEMPLATE:
# ────────
# VM "master" servant de base pour créer autres VMs
# Exemple: Template "Ubuntu 22.04 Configured"
# -> Créer 10 VMs identiques en quelques minutes

# vCPU (Virtual CPU):
# ──────────────────
# CPU virtuel assigné à une VM
# 1 vCPU = 1 cœur physique (ou thread si HyperThreading)
# 
# Exemple: VM avec 4 vCPUs
# -> Peut utiliser 4 cœurs du CPU host

# VRAM (Virtual RAM):
# ──────────────────
# RAM allouée à une VM
# Prise sur RAM physique du host
# 
# Exemple: VM avec 8GB vRAM
# -> Utilise 8GB de la RAM physique du host

# VMDK (Virtual Machine Disk):
# ───────────────────────────
# Format de fichier pour disques virtuels VMware
# Contient système d'exploitation et données de la VM
# 
# Types:
# • Thick Provisioned: Espace réservé immédiatement
# • Thin Provisioned: Espace alloué dynamiquement

# OVF/OVA (Open Virtualization Format):
# ─────────────────────────────────────
# Format standard pour exporter/importer VMs
# • OVF: Ensemble de fichiers
# • OVA: Archive unique (plus facile à partager)

# vNIC (Virtual Network Interface Card):
# ──────────────────────────────────────
# Carte réseau virtuelle pour VM
# Se comporte comme carte réseau physique

# vSwitch (Virtual Switch):
# ────────────────────────
# Switch réseau virtuel
# Connecte VMs entre elles et au réseau physique


# ═══ 1.5 COMMENT FONCTIONNE LA VIRTUALISATION? ═══

# COMPOSANTS CLÉS:
# ═══════════════

# 1. VIRTUALISATION CPU:
# ─────────────────────
# 
# Physique: Intel i7 8 cœurs
# 
# Hyperviseur divise:
# VM1: 2 vCPUs (cœurs 1-2)
# VM2: 4 vCPUs (cœurs 3-6)
# VM3: 2 vCPUs (cœurs 7-8)
# 
# Technologies Intel/AMD:
# • Intel VT-x (Virtualization Technology)
# • AMD-V (AMD Virtualization)
# -> Extensions CPU qui accélèrent virtualisation
# -> OBLIGATOIRES pour VMware moderne


# 2. VIRTUALISATION MÉMOIRE:
# ─────────────────────────
# 
# RAM Physique: 32GB
# 
# Allocation:
# • Hyperviseur: 4GB
# • VM1: 8GB
# • VM2: 12GB
# • VM3: 6GB
# • Libre: 2GB
# 
# Techniques optimisation:
# • Memory Ballooning: Récupérer RAM non utilisée
# • Memory Compression: Compresser pages mémoire
# • Memory Sharing: Partager pages identiques (ex: même OS)


# 3. VIRTUALISATION STOCKAGE:
# ──────────────────────────
# 
# Disque Physique: 1TB SSD
# 
# Disques virtuels:
# VM1: ubuntu.vmdk (50GB)
# VM2: windows.vmdk (100GB)
# VM3: centos.vmdk (80GB)
# 
# Types provisioning:
# • Thick Eager Zeroed: Tout l'espace alloué + zéros écrits
#   -> Performance max, sécurité max
# • Thick Lazy Zeroed: Espace alloué, zéros à la demande
#   -> Performance moyenne
# • Thin: Espace alloué dynamiquement
#   -> Économie espace, performance réduite


# 4. VIRTUALISATION RÉSEAU:
# ────────────────────────
# 
# Carte physique: eth0
# 
# vSwitch crée réseau virtuel:
# VM1 -> vNIC1 -> vSwitch -> eth0 -> Internet
# VM2 -> vNIC2 -> vSwitch -> eth0 -> Internet
# VM3 -> vNIC3 -> vSwitch -> eth0 -> Internet
# 
# Modes réseau (détaillés Partie 4):
# • Bridged: VM = ordinateur physique réseau
# • NAT: VM derrière routeur virtuel
# • Host-Only: VM communique seulement avec host


# ═══ 1.6 CAS D'USAGE VIRTUALISATION ═══

# QUAND UTILISER VMWARE?
# ═════════════════════

# 1. DÉVELOPPEMENT LOGICIEL:
# ─────────────────────────
# Problème: Développer app qui doit fonctionner sur:
# - Windows 10
# - Windows Server 2019
# - Ubuntu 20.04
# - CentOS 8
# 
# Solution VMware:
# PC Windows 10 (host)
# -> VM Ubuntu 20.04 (test app sur Linux)
# -> VM CentOS 8 (test app sur CentOS)
# -> VM Windows Server 2019 (test app sur serveur)
# 
# Avantages:
# [OK] Tester sur tous OS sans acheter 4 PC
# [OK] Snapshots avant tests (rollback si problème)
# [OK] Environnements isolés (pas de conflit)


# 2. FORMATION ET CERTIFICATION:
# ──────────────────────────────
# Étudiant préparant certification LPIC/RHCSA
# 
# Setup VMware:
# Host: Laptop Windows/Ubuntu
# VM1: Ubuntu Server (pratique commandes)
# VM2: CentOS (pratique RedHat-based)
# VM3: Debian (pratique Debian-based)
# 
# Avantages:
# [OK] Casser système sans risque (snapshot!)
# [OK] Recréer environnements examens
# [OK] Pratique administration sans serveur physique


# 3. TESTS DE SÉCURITÉ (PENTESTING):
# ──────────────────────────────────
# Ethical hacker testant sécurité
# 
# Lab VMware:
# Host: Laptop
# VM1: Kali Linux (outils pentesting)
# VM2: Metasploitable (cible vulnérable)
# VM3: Windows 10 (test malwares)
# Réseau: Isolé (pas d'accès Internet)
# 
# Avantages:
# [OK] Environnement isolé (pas de dégâts réseau réel)
# [OK] Snapshots pour recommencer tests
# [OK] Malware analysis en sécurité


# 4. CONSOLIDATION SERVEURS (ENTREPRISE):
# ───────────────────────────────────────
# PME avec 8 serveurs physiques vieillissants
# 
# Migration VMware:
# Avant: 8 serveurs physiques (sous-utilisés)
# Après: 2 serveurs ESXi avec 8 VMs
# 
# Bénéfices:
# [OK] Économie: -75% coûts hardware
# [OK] Énergie: -60% consommation électrique
# [OK] Espace: -75% espace rack
# [OK] Maintenance: Centralisée
# [OK] Haute disponibilité: vMotion, HA


# 5. DISASTER RECOVERY (REPRISE APRÈS SINISTRE):
# ──────────────────────────────────────────────
# Plan de secours en cas de panne datacenter
# 
# Stratégie VMware:
# Site principal: Cluster ESXi avec VMs production
# Site backup: Cluster ESXi distant
# Réplication: VMs répliquées en temps réel
# 
# Sinistre (incendie, inondation):
# -> Activation site backup en <30 minutes
# -> Business continuity assurée


# 6. CLOUD HYBRIDE:
# ────────────────
# Mix infrastructure on-premise + cloud
# 
# Architecture:
# Datacenter local: VMware vSphere
# Cloud AWS: VMware Cloud on AWS
# 
# Workload migration:
# VMs déplacées entre on-premise <-> cloud selon besoins
# (vMotion fonctionne même vers cloud!)


# ═══ 1.7 PRÉREQUIS HARDWARE POUR VMWARE ═══

# VÉRIFICATIONS AVANT INSTALLATION:
# ═════════════════════════════════

# 1. CPU COMPATIBLE:
# ─────────────────
# OBLIGATOIRE:
# [OK] Architecture 64-bit (x86-64)
# [OK] Extensions virtualisation:
#   - Intel: VT-x (Virtualization Technology)
#   - AMD: AMD-V
# 
# RECOMMANDÉ:
# [OK] Multi-cœurs (4+ cœurs)
# [OK] Fréquence élevée (2.5+ GHz)
# 
# Vérifier sur Linux:
# Pour Intel VT-x:
grep -E 'vmx' /proc/cpuinfo
# Si résultat -> VT-x supporté
# 
# Pour AMD-V:
grep -E 'svm' /proc/cpuinfo
# Si résultat -> AMD-V supporté
# 
# Activer dans BIOS si désactivé:
# 1. Redémarrer PC
# 2. Entrer BIOS (F2, F10, DEL selon PC)
# 3. Chercher "Virtualization Technology" ou "VT-x/AMD-V"
# 4. Activer (Enabled)
# 5. Sauvegarder et redémarrer


# 2. RAM (MÉMOIRE):
# ────────────────
# 
# Minimums:
# • VMware Workstation host: 4GB (mais 8GB+ recommandé)
# • VMware ESXi: 4GB (mais 8GB+ recommandé)
# 
# Par VM:
# • Linux serveur minimal: 1GB
# • Ubuntu Desktop: 4GB
# • Windows 10: 4GB
# • Windows Server: 4GB
# 
# Calcul total:
# Host: 16GB RAM
# VM1 Ubuntu: 4GB
# VM2 Windows: 4GB
# Hyperviseur: 2GB
# OS hôte (si Type 2): 4GB
# TOTAL utilisé: 14GB
# Libre: 2GB (OK)
# 
# Règle: Minimum 25% RAM libre pour host


# 3. STOCKAGE (DISQUE):
# ────────────────────
# 
# Types:
# • HDD (Hard Disk Drive): Lent mais économique
# • SSD (Solid State Drive): RAPIDE, recommandé
# • NVMe SSD: Très rapide, idéal
# 
# Espace nécessaire:
# • VMware Workstation: 2GB
# • VMware ESXi: 8GB
# 
# Par VM:
# • Linux minimal: 10-20GB
# • Ubuntu Desktop: 25GB
# • Windows 10: 40-60GB
# • Windows Server: 40GB
# 
# Exemple setup:
# Disque: 500GB SSD
# - Host OS: 100GB
# - VMware: 2GB
# - VM1 Ubuntu: 50GB
# - VM2 Windows: 80GB
# - VM3 CentOS: 50GB
# - Libre: 218GB


# 4. RÉSEAU:
# ─────────
# • Carte réseau Ethernet ou WiFi
# • Pour production: Minimum 1Gbps (Gigabit)
# • Pour labs: 100Mbps acceptable


# CONFIGURATIONS RECOMMANDÉES:
# ═══════════════════════════

# ÉTUDIANT / DÉVELOPPEUR:
# ──────────────────────
# CPU: Intel i5/i7 ou AMD Ryzen 5/7 (4+ cœurs)
# RAM: 16GB
# Disque: 256GB SSD
# Réseau: WiFi ou Ethernet
# -> Peut exécuter 2-3 VMs simultanément

# ADMINISTRATEUR SYSTÈME (LAB):
# ────────────────────────────
# CPU: Intel i7/i9 ou AMD Ryzen 7/9 (8+ cœurs)
# RAM: 32GB
# Disque: 512GB NVMe SSD
# Réseau: Gigabit Ethernet
# -> Peut exécuter 5-8 VMs simultanément

# SERVEUR PRODUCTION (ESXi):
# ─────────────────────────
# CPU: Intel Xeon ou AMD EPYC (16+ cœurs)
# RAM: 128GB+
# Disque: RAID 10 avec SSDs enterprise
# Réseau: Dual 10Gbps
# -> Peut exécuter 50+ VMs simultanément


# ═══ 1.8 VERSIONS VMWARE WORKSTATION ═══

# WORKSTATION PRO vs PLAYER:
# ═════════════════════════

# VMware Workstation Player (GRATUIT):
# ───────────────────────────────────
# Fonctionnalités:
# [OK] Créer et exécuter VMs
# [OK] 1 VM à la fois
# [OK] Snapshots (1 seul)
# [OK] Réseau basique (NAT, Bridged, Host-Only)
# [X] Pas de clones
# [X] Pas de snapshots multiples
# [X] Pas d'intégration vSphere
# 
# Idéal pour:
# • Étudiants
# • Usage personnel
# • Tests basiques

# VMware Workstation Pro (PAYANT ~300€):
# ──────────────────────────────────────
# Fonctionnalités:
# [OK] Toutes fonctionnalités Player +
# [OK] VMs multiples simultanées
# [OK] Snapshots illimités avec arbre
# [OK] Clones (Full et Linked)
# [OK] Réseau avancé (teams, VLANs)
# [OK] Intégration vSphere/ESXi
# [OK] Mode Unity (apps VM dans host)
# [OK] Partage VMs sur réseau
# [OK] Enregistrement vidéo VM
# [OK] USB 3.1 support
# [OK] API REST
# 
# Idéal pour:
# • Professionnels
# • Développeurs
# • Administrateurs systèmes

# Tableau comparatif:
# ┌───────────────────────┬─────────┬─────────┐
# │ Fonctionnalité        │ Player  │   Pro   │
# ├───────────────────────┼─────────┼─────────┤
# │ Créer VMs             │    [OK]    │    [OK]    │
# │ VMs simultanées       │    [X]    │    [OK]    │
# │ Snapshots             │  1 seul │ Illimité│
# │ Clones                │    [X]    │    [OK]    │
# │ Réseau avancé         │    [X]    │    [OK]    │
# │ Mode Unity            │    [X]    │    [OK]    │
# │ Intégration vSphere   │    [X]    │    [OK]    │
# │ Prix                  │ Gratuit │  ~300€  │
# └───────────────────────┴─────────┴─────────┘


# VERSIONS HISTORIQUES:
# ════════════════════

# v17.x (2023): Workstation 17 Pro
# • Support Windows 11, Ubuntu 22.04
# • Meilleure performance graphique
# • Support TPM 2.0 pour Windows 11

# v16.x (2021): Workstation 16 Pro
# • Support DirectX 11, OpenGL 4.1
# • Containeurs support

# v15.x (2019): Workstation 15 Pro
# • Support 4K displays
# • Support UEFI Secure Boot


# ═══ 1.9 LICENCES VMWARE ═══

# MODÈLES DE LICENCES:
# ═══════════════════

# VMware Workstation Player:
# ─────────────────────────
# • GRATUIT pour usage personnel
# • PAYANT pour usage commercial
# • Pas de support technique

# VMware Workstation Pro:
# ──────────────────────
# • Licence perpétuelle (~300€)
# • 1 licence = 1 ordinateur
# • Updates mineures incluses (ex: 17.0 -> 17.5)
# • Updates majeures payantes (ex: 17.x -> 18.x)
# • Support technique 90 jours

# VMware ESXi:
# ───────────
# • Version GRATUITE avec limitations:
#   [X] Pas de vCenter
#   [X] Pas de vMotion
#   [X] Pas de HA/DRS
#   [OK] Snapshots
#   [OK] VMs illimitées
# 
# • Versions payantes (par socket CPU):
#   - Essentials (~600€/an): 3 hosts max, vCenter included
#   - Standard (~1000€/an): Features avancées
#   - Enterprise Plus (~4000€/an): Toutes features


# LICENCES ÉDUCATION:
# ══════════════════

# VMware Academic Program:
# • Licences gratuites pour:
#   - Étudiants
#   - Enseignants
#   - Institutions éducatives
# • Accès à:
#   - Workstation Pro
#   - Fusion Pro
#   - vSphere (avec restrictions)
# 
# S'inscrire: vmware.com/academic


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 2: COMPRENDRE L'ARCHITECTURE VMWARE
# ═══════════════════════════════════════════════════════════════════


# ═══ 2.1 ARCHITECTURE GLOBALE ═══

# VUE D'ENSEMBLE:
# ══════════════

# ┌─────────────────────────────────────────────────────────────┐
# │                    NIVEAU UTILISATEUR                        │
# │                                                              │
# │   Applications    Applications    Applications              │
# │   Guest OS        Guest OS        Guest OS                  │
# │   ┌──────────┐    ┌──────────┐    ┌──────────┐            │
# │   │   VM 1   │    │   VM 2   │    │   VM 3   │            │
# │   │  Ubuntu  │    │ Windows  │    │  CentOS  │            │
# │   └──────────┘    └──────────┘    └──────────┘            │
# ├─────────────────────────────────────────────────────────────┤
# │                 NIVEAU VIRTUALISATION                        │
# │                                                              │
# │              VMware Hyperviseur (ESXi/Workstation)          │
# │   • Gestion CPU      • Gestion Mémoire                      │
# │   • Gestion Réseau   • Gestion Stockage                     │
# │   • Scheduler        • Resource Allocation                  │
# ├─────────────────────────────────────────────────────────────┤
# │                   NIVEAU MATÉRIEL                            │
# │                                                              │
# │   CPU     RAM     Disque     Réseau     Périphériques      │
# │  (Intel/  (DDR4)  (SSD/HDD)  (NIC)     (USB, GPU...)       │
# │   AMD)                                                       │
# └─────────────────────────────────────────────────────────────┘


# ═══ 2.2 COMPOSANTS HYPERVISEUR VMWARE ═══

# VMKERNEL:
# ════════
# Cœur de l'hyperviseur VMware
# Fonctions:
# • Scheduler CPU (qui utilise CPU quand)
# • Memory management (allocation RAM)
# • I/O stack (accès disque/réseau)
# • Device drivers (pilotes matériel)

# VMFS (Virtual Machine File System):
# ══════════════════════════════════
# Système de fichiers spécialisé pour VMs
# Fonctionnalités:
# • Fichiers énormes (VMs de plusieurs TB)
# • Accès concurrent (plusieurs ESXi accèdent même datastore)
# • Journaling (récupération après crash)
# • Support thin provisioning

# vSWITCH (Virtual Switch):
# ════════════════════════
# Switch réseau virtuel interne
# Connecte VMs entre elles et vers réseau physique

# VMNIC (Physical Network Adapter):
# ════════════════════════════════
# Carte réseau physique du host
# Uplink vers réseau externe


# ═══ 2.3 FORMATS DE FICHIERS VM ═══

# FICHIERS PRINCIPAUX:
# ═══════════════════

# .VMX (Virtual Machine Configuration):
# ────────────────────────────────────
# Fichier texte contenant configuration VM
# Exemple: Ubuntu.vmx
# 
# Contenu:
# .encoding = "UTF-8"
# displayName = "Ubuntu 22.04"
# guestOS = "ubuntu-64"
# memSize = "4096"      # 4GB RAM
# numvcpus = "2"        # 2 vCPUs
# scsi0:0.fileName = "Ubuntu.vmdk"
# ethernet0.present = "TRUE"
# ethernet0.connectionType = "nat"

# .VMDK (Virtual Machine Disk):
# ────────────────────────────
# Disque dur virtuel
# Contient système d'exploitation et données
# 
# Types:
# 1. Monolithic Sparse: 1 fichier, taille dynamique
# 2. Monolithic Flat: 1 fichier, taille fixe
# 3. Split Sparse: Plusieurs fichiers de 2GB, dynamique
# 4. Split Flat: Plusieurs fichiers de 2GB, fixe
# 
# Exemple: Ubuntu.vmdk (descriptor file)
#         Ubuntu-flat.vmdk (actual data)

# .VMEM (Virtual Machine Memory):
# ──────────────────────────────
# État mémoire RAM de la VM
# Créé quand VM suspendue
# Taille = RAM allouée à VM

# .VMSN (Snapshot State):
# ──────────────────────
# État snapshot (CPU, mémoire, disque)
# Exemple: Ubuntu-Snapshot1.vmsn

# .VMSD (Snapshot Metadata):
# ─────────────────────────
# Métadonnées snapshots (liste, arbre)
# Exemple: Ubuntu.vmsd

# .NVRAM (BIOS Settings):
# ──────────────────────
# Settings BIOS/UEFI de la VM
# Exemple: Ubuntu.nvram

# .LOG (Log Files):
# ────────────────
# Logs hyperviseur pour cette VM
# vmware.log, vmware-1.log, vmware-2.log...

# EXEMPLE STRUCTURE COMPLÈTE VM:
# ═════════════════════════════

# Ubuntu/
# ├── Ubuntu.vmx              (config)
# ├── Ubuntu.vmxf             (supplemental config)
# ├── Ubuntu.vmdk             (disk descriptor)
# ├── Ubuntu-flat.vmdk        (actual disk data - 50GB)
# ├── Ubuntu.nvram            (BIOS settings)
# ├── Ubuntu.vmsd             (snapshot metadata)
# ├── Ubuntu-Snapshot1.vmsn   (snapshot 1 state)
# ├── Ubuntu-Snapshot1.vmdk   (snapshot 1 disk)
# ├── Ubuntu.vmem             (suspended memory - si suspendue)
# ├── vmware.log              (current log)
# ├── vmware-1.log            (previous log)
# └── vmware-2.log            (older log)


# ═══ 2.4 CYCLE DE VIE D'UNE VM ═══

# ÉTATS D'UNE VM:
# ══════════════

# 1. POWERED OFF (Éteinte):
# ────────────────────────
# VM existe mais n'utilise aucune ressource
# Seulement fichiers sur disque
# 
# Ressources utilisées:
# • CPU: 0%
# • RAM: 0MB
# • Disque: Taille .vmdk

# 2. POWERED ON (Allumée):
# ───────────────────────
# VM en cours d'exécution
# OS guest actif
# 
# Ressources utilisées:
# • CPU: Selon charge VM
# • RAM: Selon allocation (ex: 4GB)
# • Disque: .vmdk + .vmem + logs

# 3. SUSPENDED (Suspendue):
# ────────────────────────
# VM "gelée" dans état actuel
# RAM sauvegardée dans .vmem
# Reprise ultra-rapide
# 
# Ressources utilisées:
# • CPU: 0%
# • RAM: 0MB (sauvegardée sur disque)
# • Disque: .vmdk + .vmem (taille RAM)

# 4. PAUSED (Pause):
# ─────────────────
# VM en pause temporaire (rare)
# RAM reste en mémoire physique
# 
# Ressources utilisées:
# • CPU: 0%
# • RAM: Toujours allouée (ex: 4GB)


# OPÉRATIONS VM:
# ═════════════

# BOOT (Démarrage):
# ────────────────
# Powered Off -> Powered On
# 1. Hyperviseur charge .vmx
# 2. Alloue ressources (CPU, RAM)
# 3. Attache disques (.vmdk)
# 4. Initialise vNICs
# 5. BIOS virtuel démarre
# 6. OS guest boot

# SHUTDOWN (Arrêt):
# ────────────────
# Powered On -> Powered Off
# • Graceful: OS guest s'éteint proprement
# • Hard: Force power off (comme débrancher)

# SUSPEND (Suspension):
# ────────────────────
# Powered On -> Suspended
# 1. Fige état CPU
# 2. Sauvegarde RAM -> .vmem
# 3. Libère ressources physiques

# RESUME (Reprise):
# ────────────────
# Suspended -> Powered On
# 1. Restaure RAM depuis .vmem
# 2. Restaure état CPU
# 3. VM continue exactement où elle était

# RESET (Redémarrage):
# ───────────────────
# Hard reset (comme bouton reset PC)
# VM redémarre sans shutdown propre
# [ATTENTION] Risque corruption données


# ═══ 2.5 RESSOURCES ET ALLOCATION ═══

# OVERCOMMITMENT (Sur-allocation):
# ════════════════════════════════

# Concept: Allouer PLUS de ressources virtuelles que disponibles physiquement
# 
# Exemple CPU:
# Host: 8 cœurs physiques
# VM1: 4 vCPUs
# VM2: 4 vCPUs
# VM3: 4 vCPUs
# TOTAL: 12 vCPUs (150% overcommit)
# 
# Pourquoi ça marche?
# Les VMs n'utilisent PAS 100% CPU en permanence!
# Hyperviseur partage intelligemment

# Exemple RAM:
# Host: 16GB physique
# VM1: 8GB
# VM2: 8GB
# VM3: 4GB
# TOTAL: 20GB (125% overcommit)
# 
# Techniques hyperviseur:
# • Memory Ballooning
# • Memory Compression
# • Memory Swapping (lent!)

# LIMITES OVERCOMMIT:
# ──────────────────
# CPU: Overcommit OK jusqu'à 2:1 (2 vCPUs par core)
# RAM: Éviter overcommit >100% (swapping = lent)


# SHARES, RESERVATIONS, LIMITS:
# ════════════════════════════

# SHARES (Parts):
# ──────────────
# Priorité relative entre VMs
# 
# Exemple:
# Host: 16GB RAM
# VM1: 2000 shares
# VM2: 4000 shares (double priority)
# VM3: 2000 shares
# 
# Si contention (pas assez RAM):
# VM2 obtient 2× plus RAM que VM1/VM3

# RESERVATION:
# ───────────
# Ressource GARANTIE pour VM
# 
# Exemple:
# VM critique: 4GB RAM reserved
# -> Hyperviseur DOIT garder 4GB dispo
# -> VM démarre seulement si 4GB disponibles

# LIMIT:
# ─────
# Maximum ressource utilisable
# 
# Exemple:
# VM test: CPU limit 50%
# -> Ne peut jamais utiliser >50% CPU
# -> Même si CPU idle


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 1: INTRODUCTION ET CONCEPTS FONDAMENTAUX
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 1:
# 
# [OK] Pourquoi virtualisation existe (économie ressources)
# [OK] VMware: leader mondial virtualisation
# [OK] Types hyperviseurs: Type 1 (bare-metal) vs Type 2 (hosted)
# [OK] Terminologie: Host, Guest, VM, Snapshot, Clone
# [OK] Comment fonctionne virtualisation (CPU, RAM, Storage, Network)
# [OK] Cas d'usage: Dev, Formation, Production, DR
# [OK] Prérequis hardware: CPU VT-x/AMD-V, RAM, Storage
# [OK] Workstation Pro vs Player
# [OK] Architecture VMware: Vmkernel, VMFS, vSwitch
# [OK] Formats fichiers: .vmx, .vmdk, .vmem, .vmsn
# [OK] Cycle de vie VM: States, Operations
# [OK] Allocation ressources: Overcommit, Shares, Reservations
# 
# [OBJECTIF] PROCHAINE PARTIE:
# Partie 2 couvre Installation et Configuration de VMware
# (Installation Workstation, Configuration initiale, Préférences)
# 
# [GUIDE] Pour approfondir:
# • Documentation VMware: docs.vmware.com
# • VMware Communities: communities.vmware.com
# • VMware Hands-on Labs: hol.vmware.com (labs gratuits online)
# 
# --- FIN PARTIE 1 ---

# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 2: INSTALLATION ET CONFIGURATION
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 3: INSTALLATION VMWARE WORKSTATION
# ═══════════════════════════════════════════════════════════════════


# ═══ 3.1 PRÉREQUIS ET VÉRIFICATIONS ═══

# VÉRIFIER COMPATIBILITÉ CPU (Linux Ubuntu):
# ══════════════════════════════════════════

# 1. Vérifier architecture 64-bit:
uname -m
# Résultat attendu: x86_64
# Si i686 ou i386 -> CPU 32-bit (NON COMPATIBLE!)

# 2. Vérifier extensions virtualisation:
# Pour Intel VT-x:
egrep -o 'vmx' /proc/cpuinfo | wc -l
# Si > 0 -> VT-x supporté [OK]

# Pour AMD-V:
egrep -o 'svm' /proc/cpuinfo | wc -l
# Si > 0 -> AMD-V supporté [OK]

# Si résultat = 0:
# -> Extensions virtualisation désactivées dans BIOS
# -> Redémarrer et activer dans BIOS

# 3. Vérifier virtualisation active:
kvm-ok
# Si "KVM acceleration can be used" -> OK [OK]
# Si commande introuvable:
sudo apt install cpu-checker
kvm-ok


# ACTIVER VIRTUALISATION DANS BIOS:
# ═════════════════════════════════

# Étapes générales:
# 1. Redémarrer PC
# 2. Appuyer F2, F10, F12, ou DEL pendant boot (dépend fabricant)
# 3. Naviguer vers "Advanced" ou "CPU Configuration"
# 4. Chercher option:
#    - Intel: "Intel Virtualization Technology" ou "VT-x"
#    - AMD: "SVM Mode" ou "AMD-V"
# 5. Changer de "Disabled" à "Enabled"
# 6. Sauvegarder (F10) et Exit

# Fabricants spécifiques:
# • Dell: F2 -> Advanced -> Virtualization -> Enable
# • HP: F10 -> Security -> System Security -> Enable VT-x
# • Lenovo: F1 -> Security -> Virtualization -> Enable
# • ASUS: F2 -> Advanced -> CPU Configuration -> Enable


# VÉRIFIER RESSOURCES DISPONIBLES:
# ════════════════════════════════

# RAM totale:
free -h
# Vérifier "total" ligne "Mem:"
# Minimum 8GB pour VMware + 2-3 VMs

# Espace disque disponible:
df -h
# Vérifier partition où installer VMware
# Recommandé: 100GB+ libre

# CPU info:
lscpu
# Vérifier:
# - Architecture: x86_64
# - CPU(s): Nombre cœurs (minimum 4)
# - Thread(s) per core: 2 si HyperThreading


# ═══ 3.2 TÉLÉCHARGER VMWARE WORKSTATION ═══

# WORKSTATION PLAYER (GRATUIT):
# ════════════════════════════

# Site officiel:
# https://www.vmware.com/products/workstation-player.html

# Cliquer "Download Now"
# Sélectionner:
# - VMware Workstation Player for Linux
# - Version: Latest (ex: 17.5.0)
# - File: VMware-Player-17.5.0-XXXXXXX.x86_64.bundle

# Exemple fichier téléchargé:
# VMware-Player-17.5.0-22583795.x86_64.bundle
# Taille: ~500MB


# WORKSTATION PRO (PAYANT):
# ═════════════════════════

# Site officiel:
# https://www.vmware.com/products/workstation-pro.html

# Options:
# 1. Acheter licence (~300€)
# 2. Essai gratuit 30 jours (full features)
# 3. Licence éducation (gratuit pour étudiants)

# Téléchargement similaire Player:
# VMware-Workstation-17.5.0-XXXXXXX.x86_64.bundle


# VÉRIFIER INTÉGRITÉ FICHIER:
# ═══════════════════════════

# Checksum SHA256 (optionnel mais recommandé):
sha256sum VMware-Player-*.bundle
# Comparer avec checksum officiel sur site VMware

# Vérifier permissions fichier:
ls -lh VMware-Player-*.bundle
# Si pas exécutable, ajouter permission:
chmod +x VMware-Player-*.bundle


# ═══ 3.3 INSTALLER VMWARE WORKSTATION SUR UBUNTU ═══

# INSTALLATION PRÉREQUIS SYSTÈME:
# ═══════════════════════════════

# Mettre à jour système:
sudo apt update
sudo apt upgrade -y

# Installer build-essential (compilateurs):
sudo apt install -y build-essential

# Installer headers Linux (OBLIGATOIRE pour modules kernel):
sudo apt install -y linux-headers-$(uname -r)

# Vérifier installation headers:
ls /usr/src/linux-headers-$(uname -r)
# Doit afficher dossier headers


# LANCER INSTALLATION VMWARE:
# ═══════════════════════════

# Méthode 1: Graphique (double-clic fichier)
# ──────────────────────────────────────────
# 1. Naviguer vers dossier Téléchargements
# 2. Double-cliquer fichier .bundle
# 3. Entrer password sudo
# 4. Suivre assistant graphique

# Méthode 2: Terminal (recommandée)
# ─────────────────────────────────
cd ~/Downloads  # ou dossier avec fichier

# Lancer installeur:
sudo ./VMware-Player-17.5.0-*.bundle

# Installation démarre:
# Extracting VMware Installer...
# Installing VMware Workstation Player...


# ASSISTANT INSTALLATION:
# ══════════════════════

# Écran 1: Welcome
# ───────────────
# [Next]

# Écran 2: End User License Agreement
# ───────────────────────────────────
# [x] I accept the terms in the license agreement
# [Next]

# Écran 3: Custom Setup
# ────────────────────
# Installation directory: /opt/vmware/  (laisser défaut)
# 
# Options:
# [x] Enhanced Keyboard Driver
#   -> Meilleur support clavier dans VMs
#   -> Recommandé: Cocher
# 
# [Next]

# Écran 4: User Experience Improvement Program
# ────────────────────────────────────────────
# Envoyer données usage anonymes à VMware
# [ ] Help improve VMware...
# -> Votre choix (pas obligatoire)
# 
# [Next]

# Écran 5: Shortcuts
# ─────────────────
# [x] Desktop
# [x] Applications Menu
# -> Créer raccourcis pour lancement facile
# 
# [Next]

# Écran 6: Ready to Install
# ────────────────────────
# Résumé configuration
# [Install]

# Installation en cours:
# ─────────────────────
# Installing VMware Workstation Player...
# [███████████████████████████         ] 75%
# 
# Durée: 2-5 minutes


# COMPILATION MODULES KERNEL:
# ═══════════════════════════

# Après installation, VMware compile modules:
# Would you like this program to invoke the command for you now? [yes]
# -> Taper: yes
# 
# Modules compilés:
# • vmmon (VMware Monitor)
# • vmnet (VMware Networking)
# 
# Si succès:
# Starting VMware services:
#    Virtual machine monitor                                  [  OK  ]
#    Virtual ethernet                                         [  OK  ]


# PREMIER LANCEMENT:
# ═════════════════

# Lancer VMware:
vmplayer
# Ou depuis menu Applications -> VMware Workstation Player

# Écran licence (si Pro):
# ──────────────────────
# Enter license key: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
# Ou: [Use VMware Workstation Player for free]
# -> Cliquer pour version gratuite

# Accord licence:
# ──────────────
# [x] I accept the terms in the license agreement
# [OK]

# Écran principal s'ouvre! [OK]


# ERREURS COURANTES INSTALLATION:
# ═══════════════════════════════

# ERREUR 1: "Failed to build vmmon module"
# ────────────────────────────────────────
# Cause: Headers kernel manquants
# 
# Solution:
sudo apt install linux-headers-$(uname -r)
sudo vmware-modconfig --console --install-all

# ERREUR 2: "Unable to install all modules"
# ─────────────────────────────────────────
# Cause: Secure Boot activé
# 
# Solutions:
# Option A: Désactiver Secure Boot (BIOS)
# 1. Redémarrer -> BIOS
# 2. Security -> Secure Boot -> Disabled
# 
# Option B: Signer modules (complexe)
# Créer clé et signer vmmon/vmnet modules

# ERREUR 3: "gcc: command not found"
# ──────────────────────────────────
# Cause: build-essential pas installé
# 
# Solution:
sudo apt install build-essential

# ERREUR 4: Permission denied
# ──────────────────────────
# Cause: Fichier .bundle pas exécutable
# 
# Solution:
chmod +x VMware-Player-*.bundle


# ═══ 3.4 CONFIGURATION INITIALE ═══

# INTERFACE WORKSTATION PLAYER:
# ════════════════════════════

# Au lancement, interface montre:
# 
# ┌─────────────────────────────────────────────────────────┐
# │ File  Player  Help                                      │
# ├─────────────────────────────────────────────────────────┤
# │                                                          │
# │   Home                                                   │
# │                                                          │
# │   ┌────────────────────────────────────────────┐       │
# │   │                                             │       │
# │   │    Welcome to VMware Workstation Player    │       │
# │   │                                             │       │
# │   │    [Create a New Virtual Machine]          │       │
# │   │                                             │       │
# │   │    [Open a Virtual Machine]                │       │
# │   │                                             │       │
# │   └────────────────────────────────────────────┘       │
# │                                                          │
# │   Recent Virtual Machines                                │
# │   (vide au début)                                        │
# │                                                          │
# └─────────────────────────────────────────────────────────┘


# PRÉFÉRENCES GLOBALES:
# ════════════════════

# Accès: Player -> Preferences (ou Ctrl+P)

# Onglet: Workspace
# ────────────────
# Default location for virtual machines:
# /home/votre_user/vmware
# -> Dossier où VMs seront sauvegardées
# -> Recommandé: Partition avec beaucoup d'espace
# 
# Option: Remember opened virtual machines between sessions
# [x] -> Réouvrir VMs précédentes au lancement

# Onglet: Input
# ────────────
# Cursor settings:
# [x] Grab keyboard and mouse input on mouse click
# -> Capturer entrées au clic dans VM
# [x] Optimize mouse for games
# -> Meilleure performance souris jeux

# Onglet: Hot Keys
# ───────────────
# Capture input: Ctrl+G (défaut)
# -> Combinaison pour capturer clavier/souris dans VM
# Release input: Ctrl+Alt (défaut)
# -> Combinaison pour libérer clavier/souris

# Onglet: Display
# ──────────────
# [x] Autofit window
# -> Redimensionner fenêtre VM automatiquement
# [x] Autofit guest
# -> Ajuster résolution guest à fenêtre

# Onglet: Unity (si Workstation Pro)
# ──────────────────────────────────
# Mode Unity: Applications VM dans host
# (Non disponible Player gratuit)

# Onglet: Updates
# ──────────────
# Check for product updates on startup:
# [x] -> Vérifier mises à jour au lancement
# Download all components now
# -> Télécharger outils VMware Tools


# CONFIGURATION RÉSEAU PAR DÉFAUT:
# ════════════════════════════════

# VMware crée 3 réseaux virtuels par défaut:

# VMnet0 (Bridged):
# ────────────────
# VM connectée directement au réseau physique
# IP dans même sous-réseau que host
# Exemple: Host 192.168.1.10, VM 192.168.1.20

# VMnet1 (Host-Only):
# ──────────────────
# Réseau privé entre host et VMs
# Pas d'accès Internet
# Subnet défaut: 192.168.1.0/24

# VMnet8 (NAT):
# ────────────
# VM derrière routeur virtuel
# Accès Internet via host
# Subnet défaut: 192.168.100.0/24

# Vérifier réseaux virtuels:
# Éditer -> Virtual Network Editor
# (Nécessite mot de passe sudo)


# ═══ 3.5 INSTALLATION VMWARE TOOLS ═══

# POURQUOI VMWARE TOOLS?
# ═════════════════════

# VMware Tools = Suite de pilotes et utilitaires
# 
# Sans VMware Tools:
# [X] Résolution limitée (800×600)
# [X] Souris lente et saccadée
# [X] Pas de copier-coller host<->guest
# [X] Pas de partage fichiers
# [X] Pas de synchronisation heure
# [X] Performances réduites
# 
# Avec VMware Tools:
# [OK] Résolution dynamique (suit fenêtre)
# [OK] Souris fluide
# [OK] Copier-coller fonctionne
# [OK] Drag & drop fichiers
# [OK] Shared folders (partage dossiers)
# [OK] Time sync automatique
# [OK] Performances optimisées (I/O, réseau)


# INSTALLATION SUR VM LINUX (Ubuntu):
# ═══════════════════════════════════

# Méthode 1: Depuis dépôts (RECOMMANDÉ)
# ─────────────────────────────────────
# Ubuntu inclut open-vm-tools (open source VMware Tools)

# Dans la VM Ubuntu:
sudo apt update
sudo apt install -y open-vm-tools

# Pour support desktop/GUI:
sudo apt install -y open-vm-tools-desktop

# Redémarrer VM:
sudo reboot

# Vérifier installation:
vmware-toolbox-cmd -v
# Affiche version -> Installé [OK]


# Méthode 2: ISO VMware officiel
# ──────────────────────────────
# Si open-vm-tools ne fonctionne pas

# Dans VMware:
# 1. VM -> Install VMware Tools
# 2. ISO monté dans VM comme CD/DVD

# Dans la VM:
# 1. Monter CD:
sudo mkdir /mnt/cdrom
sudo mount /dev/cdrom /mnt/cdrom

# 2. Copier archive:
cp /mnt/cdrom/VMwareTools-*.tar.gz /tmp/

# 3. Extraire:
cd /tmp
tar xvf VMwareTools-*.tar.gz

# 4. Installer:
cd vmware-tools-distrib
sudo ./vmware-install.pl

# 5. Suivre assistant (accepter défauts)
# [ENTER] pour toutes questions

# 6. Redémarrer:
sudo reboot


# INSTALLATION SUR VM WINDOWS:
# ════════════════════════════

# Dans VMware:
# VM -> Install VMware Tools

# Dans la VM Windows:
# 1. AutoPlay s'ouvre automatiquement
# 2. Cliquer "Run setup64.exe"
# 3. Suivre assistant:
#    - [Next]
#    - Typical installation
#    - [Install]
# 4. Redémarrer Windows

# Vérifier:
# Icône VMware Tools dans system tray


# FONCTIONNALITÉS VMWARE TOOLS:
# ═════════════════════════════

# 1. SHARED FOLDERS (Partage dossiers):
# ─────────────────────────────────────
# Partager dossier host avec VM

# Configuration:
# VM -> Settings -> Options -> Shared Folders
# [x] Always enabled
# [Add] -> Ajouter dossier host

# Dans VM Linux:
# Dossiers partagés montés dans:
/mnt/hgfs/nom_dossier_partage

# Dans VM Windows:
# Dossiers dans Network -> VMware Shared Folders

# 2. COPIER-COLLER:
# ────────────────
# VM -> Settings -> Options -> Guest Isolation
# [x] Enable copy and paste

# 3. DRAG & DROP:
# ──────────────
# VM -> Settings -> Options -> Guest Isolation
# [x] Enable drag and drop

# 4. TIME SYNCHRONIZATION:
# ───────────────────────
# VM -> Settings -> Options -> VMware Tools
# [x] Synchronize guest time with host


# ═══ 3.6 STRUCTURE DOSSIERS VMWARE ═══

# DOSSIERS PRINCIPAUX:
# ═══════════════════

# /opt/vmware/
# ───────────
# Binaires VMware
# /opt/vmware/bin/vmplayer -> Exécutable principal

# /etc/vmware/
# ───────────
# Fichiers configuration système

# /usr/lib/vmware/
# ───────────────
# Bibliothèques VMware

# ~/vmware/
# ────────
# Vos machines virtuelles (défaut)
# Exemple:
# ~/vmware/
# ├── Ubuntu/
# │   ├── Ubuntu.vmx
# │   ├── Ubuntu.vmdk
# │   └── ...
# ├── Windows/
# │   ├── Windows.vmx
# │   └── ...

# /var/log/vmware/
# ───────────────
# Logs système VMware


# FICHIERS CONFIGURATION IMPORTANTS:
# ══════════════════════════════════

# ~/.vmware/preferences
# ────────────────────
# Préférences utilisateur
# 
# Exemple contenu:
# .encoding = "UTF-8"
# pref.vmplayer.firstRunDismissedVersion = "17.5.0"
# prefvmx.defaultVMPath = "/home/user/vmware"
# pref.hotkey.control = "true"
# pref.hotkey.alt = "true"

# /etc/vmware/networking
# ─────────────────────
# Configuration réseaux virtuels
# 
# Exemple:
# VERSION=1,0
# answer VNET_1_DHCP yes
# answer VNET_1_DHCP_CFG_HASH xxxxx
# answer VNET_1_HOSTONLY_NETMASK 255.255.255.0
# answer VNET_1_HOSTONLY_SUBNET 192.168.1.0


# COMMANDES VMWARE UTILES:
# ═══════════════════════

# Lancer Player:
vmplayer

# Lancer VM spécifique:
vmplayer ~/vmware/Ubuntu/Ubuntu.vmx

# Démarrer VM en arrière-plan (headless):
vmrun start ~/vmware/Ubuntu/Ubuntu.vmx nogui

# Lister VMs en cours:
vmrun list

# Arrêter VM:
vmrun stop ~/vmware/Ubuntu/Ubuntu.vmx

# Suspendre VM:
vmrun suspend ~/vmware/Ubuntu/Ubuntu.vmx

# Prendre snapshot:
vmrun snapshot ~/vmware/Ubuntu/Ubuntu.vmx snapshot1

# Vérifier status VMware services:
sudo systemctl status vmware

# Redémarrer services VMware:
sudo systemctl restart vmware


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 4: INTERFACE VMWARE WORKSTATION
# ═══════════════════════════════════════════════════════════════════


# ═══ 4.1 INTERFACE PRINCIPALE ═══

# BARRE MENU (Top):
# ════════════════

# File
# ───
# • Create a New Virtual Machine -> Nouvelle VM
# • Open -> Ouvrir VM existante (.vmx)
# • Scan for Virtual Machines -> Chercher VMs dossier
# • Close Tab -> Fermer onglet VM
# • Exit -> Quitter VMware

# Player (ou VM)
# ─────
# • Power
#   - Power On -> Démarrer VM
#   - Power Off -> Éteindre VM
#   - Suspend -> Suspendre VM
#   - Restart -> Redémarrer VM
#   - Reset -> Reset dur
# 
# • Removable Devices -> Périphériques (USB, CD/DVD)
# • Install VMware Tools -> Installer Tools
# • Send Ctrl+Alt+Del -> Envoyer dans VM
# • Snapshot (Pro)
#   - Take Snapshot -> Créer snapshot
#   - Revert to Snapshot -> Restaurer
#   - Snapshot Manager -> Gestionnaire
# • Settings -> Configuration VM

# Help
# ───
# • Help Contents -> Aide
# • About -> Version VMware


# BARRE OUTILS (Toolbar):
# ══════════════════════

# Icônes principales:
# [[BLACK_RIGHT-POINTING_TRIANGLE]] Power On -> Démarrer VM
# [[BLACK_SQUARE]] Power Off -> Arrêter VM
# [[DOUBLE_VERTICAL_BAR]] Suspend -> Suspendre
# [(sync)] Restart -> Redémarrer
# [[CAMERA]] Snapshot -> Prendre snapshot (Pro)
# [[CONFIG]] Settings -> Paramètres VM


# SIDEBAR (Gauche):
# ════════════════

# Library
# ──────
# Liste toutes VMs disponibles
# 
# Favorites
# ────────
# VMs favorites (accès rapide)
# Clic droit VM -> Add to Favorites


# ZONE CENTRALE:
# ═════════════

# Tabs
# ───
# Onglets pour chaque VM ouverte
# Permet gérer plusieurs VMs

# Console
# ──────
# Affichage écran VM
# Interaction clavier/souris

# Status Bar (Bas)
# ───────────────
# Indicateurs:
# • [[WHITE_CIRCLE]] Powered Off / [[BLACK_RIGHT-POINTING_TRIANGLE]] Powered On
# • [[RESEAU]] État réseau
# • [[SAUVEGARDE]] Activité disque
# • [[SON]] Son


# ═══ 4.2 RACCOURCIS CLAVIER ═══

# GESTION VM:
# ══════════

# Ctrl+B -> Power On (Boot)
# Ctrl+E -> Power Off
# Ctrl+Z -> Suspend
# Ctrl+R -> Reset

# Ctrl+Alt -> Libérer souris/clavier
# Ctrl+G -> Capturer souris/clavier
# Ctrl+Alt+Insert -> Ctrl+Alt+Del dans VM

# NAVIGATION:
# ══════════

# Ctrl+T -> Nouvel onglet
# Ctrl+W -> Fermer onglet
# Ctrl+Tab -> Onglet suivant
# Ctrl+Shift+Tab -> Onglet précédent

# AFFICHAGE:
# ═════════

# Ctrl+Alt+Enter -> Plein écran
# Ctrl+Alt+F -> Fit window to guest
# Ctrl+Alt -> Quitter plein écran

# SNAPSHOTS (Pro):
# ═══════════════

# Ctrl+Shift+S -> Take Snapshot
# Ctrl+Shift+R -> Revert to Snapshot


# ═══ 4.3 PANNEAU DE CONFIGURATION VM ═══

# Accès: VM -> Settings (ou Ctrl+D)

# HARDWARE (Matériel):
# ══════════════════

# Memory
# ─────
# Slider pour allouer RAM
# Minimum: 1GB
# Recommandé: 4GB pour Ubuntu Desktop
# Maximum recommandé: 50-75% RAM host

# Processors
# ─────────
# Number of processors: 1
# Number of cores per processor: 2
# -> Total: 2 vCPUs
# 
# Recommandation:
# VMs légères: 1-2 vCPUs
# VMs desktop: 2-4 vCPUs
# VMs serveur: 4+ vCPUs

# Hard Disk
# ────────
# Type: SCSI ou NVMe
# Size: ex. 50GB
# Type allocation:
# • Store virtual disk as single file (1 fichier)
# • Split virtual disk into multiple files (2GB chacun)

# CD/DVD (IDE ou SATA)
# ───────────────────
# Use physical drive: /dev/sr0
# Use ISO image file: /path/to/ubuntu.iso
# [x] Connect at power on

# Network Adapter
# ──────────────
# Network connection:
# [WHITE_CIRCLE] Bridged -> Direct réseau physique
# [WHITE_CIRCLE] NAT -> Derrière routeur virtuel
# [WHITE_CIRCLE] Host-only -> Réseau privé avec host
# [WHITE_CIRCLE] Custom (VMnet2-9) -> Réseau custom

# USB Controller
# ─────────────
# [x] Present
# [x] Automatically connect new USB devices
# USB compatibility:
# • USB 2.0
# • USB 3.1

# Sound Card
# ─────────
# [x] Present
# Auto detect (recommandé)

# Display
# ──────
# [x] Accelerate 3D graphics
# Graphics memory: Auto (ou manuel)
# Monitors: 1 (ou 2 pour dual-screen)


# OPTIONS (Configuration):
# ═══════════════════════

# General
# ──────
# Guest Operating System: Linux
# Version: Ubuntu 64-bit
# 
# VM Name: Ubuntu
# Working directory: /home/user/vmware/Ubuntu

# VMware Tools
# ───────────
# [x] Synchronize guest time with host
# Update automatically
# Check and upgrade Tools during power cycling

# Power
# ────
# Power off: Shut down guest
# (Alternative: Power off, Suspend)
# 
# Suspend: Suspend the virtual machine
# 
# Close behavior:
# [WHITE_CIRCLE] Shut down guest
# [WHITE_CIRCLE] Suspend the virtual machine
# [WHITE_CIRCLE] Power off the virtual machine

# Shared Folders
# ─────────────
# Folder sharing:
# [WHITE_CIRCLE] Disabled
# [WHITE_CIRCLE] Always enabled
# [WHITE_CIRCLE] Enabled until next power off
# 
# [Add] -> Ajouter shared folder
# Host path: /home/user/Documents
# Name: Documents
# Attributes: [x] Enabled

# Snapshot (Pro)
# ─────────────
# Snapshot directory: Same as VM
# (Alternative: Dossier custom)

# Guest Isolation
# ──────────────
# [x] Enable copy and paste
# [x] Enable drag and drop


# ═══ 4.4 VIRTUAL NETWORK EDITOR ═══

# Accès: Edit -> Virtual Network Editor (nécessite sudo)

# GESTION RÉSEAUX VIRTUELS:
# ═════════════════════════

# Onglet: Summary
# ──────────────
# Liste tous réseaux virtuels:
# 
# Name    Type        Subnet          Connected
# VMnet0  Bridged     -               eth0
# VMnet1  Host-only   192.168.1.0     -
# VMnet8  NAT         192.168.100.0   -

# Boutons:
# [Add Network] -> Créer nouveau VMnetX
# [Remove Network] -> Supprimer VMnetX
# [Change Settings] -> Modifier (nécessite sudo)


# CONFIGURATION VMNET8 (NAT):
# ═══════════════════════════

# Sélectionner VMnet8

# Subnet IP: 192.168.100.0
# Subnet mask: 255.255.255.0
# 
# [x] Use local DHCP service
# -> VMs reçoivent IP automatiquement
# 
# [DHCP Settings]:
# Starting IP: 192.168.100.128
# Ending IP: 192.168.100.254
# Lease duration: 1800 seconds (30 min)

# [NAT Settings]:
# Gateway IP: 192.168.100.2
# 
# Port Forwarding:
# Host Port 8080 -> VM 192.168.100.10:80
# -> Rediriger port host vers VM


# CONFIGURATION VMNET1 (Host-Only):
# ═════════════════════════════════

# Sélectionner VMnet1

# Subnet IP: 192.168.1.0
# Subnet mask: 255.255.255.0
# 
# [x] Use local DHCP service
# 
# Pas de gateway (réseau isolé)


# CONFIGURATION VMNET0 (Bridged):
# ═══════════════════════════════

# Sélectionner VMnet0

# Bridged to: Automatic
# (ou sélectionner carte spécifique)
# -> eth0 (Ethernet)
# -> wlan0 (WiFi)


# ═══ 4.5 PRÉFÉRENCES AVANCÉES ═══

# MÉMOIRE:
# ═══════

# Edit -> Preferences -> Memory

# Reserved memory:
# [WHITE_CIRCLE] Fit all virtual machine memory into reserved memory
#   -> Réserver toute RAM VMs (performance max)
# [WHITE_CIRCLE] Allow most virtual machine memory to be swapped
#   -> Permettre swap (économiser RAM)
# [WHITE_CIRCLE] Allow some virtual machine memory to be swapped
#   -> Compromis (recommandé)

# Additional memory:
# Slider: Combien RAM laisser libre pour host
# Recommandé: 25% minimum


# PRIORITY:
# ════════

# Edit -> Preferences -> Priority

# Input grabbed:
# Priority when input is grabbed: High
# -> VM au premier plan = priorité haute

# Snapshot:
# Take snapshot in the background
# [x] -> Prendre snapshot sans bloquer VM


# DEVICES:
# ═══════

# Edit -> Preferences -> Devices

# USB:
# [x] Show USB devices as attached to virtual machines
# -> Montrer périphériques USB disponibles

# [x] Automatically connect new USB devices
# -> Auto-connecter nouveaux USB à VM active


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 2: INSTALLATION ET CONFIGURATION
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 2:
# 
# [OK] Vérifications prérequis (VT-x/AMD-V, RAM, Disque)
# [OK] Activation virtualisation BIOS
# [OK] Téléchargement VMware Workstation (Player/Pro)
# [OK] Installation sur Ubuntu (étapes détaillées)
# [OK] Compilation modules kernel (vmmon, vmnet)
# [OK] Configuration initiale (préférences, réseaux)
# [OK] Installation VMware Tools (open-vm-tools)
# [OK] Fonctionnalités Tools (shared folders, copy-paste, drag-drop)
# [OK] Structure dossiers VMware
# [OK] Interface Workstation (menus, toolbar, sidebar)
# [OK] Raccourcis clavier essentiels
# [OK] Panneau configuration VM (Hardware, Options)
# [OK] Virtual Network Editor (VMnet0, VMnet1, VMnet8)
# [OK] Préférences avancées (mémoire, priorité, devices)
# 
# [OBJECTIF] PROCHAINE PARTIE:
# Partie 3 couvre Création et Gestion de Machines Virtuelles
# (Créer VM, Installer OS, Clones, Snapshots, Export/Import)
# 
# --- FIN PARTIE 2 ---

# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 3: CRÉATION ET GESTION DE MACHINES VIRTUELLES
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 5: CRÉER PREMIÈRE MACHINE VIRTUELLE
# ═══════════════════════════════════════════════════════════════════


# ═══ 5.1 PRÉPARER L'INSTALLATION ═══

# TÉLÉCHARGER ISO SYSTÈME D'EXPLOITATION:
# ═══════════════════════════════════════

# Ubuntu Server 22.04 LTS:
# ───────────────────────
# Site: https://ubuntu.com/download/server
# Fichier: ubuntu-22.04.3-live-server-amd64.iso
# Taille: ~1.5GB
# SHA256: Vérifier checksum

# Ubuntu Desktop 22.04 LTS:
# ────────────────────────
# Site: https://ubuntu.com/download/desktop
# Fichier: ubuntu-22.04.3-desktop-amd64.iso
# Taille: ~4.6GB

# Autres distributions:
# ────────────────────
# • Debian: debian.org/distrib/netinst
# • CentOS Stream: centos.org/download
# • Fedora: fedoraproject.org/workstation
# • Kali Linux: kali.org/get-kali

# Windows (légalement):
# ────────────────────
# • Windows 10: microsoft.com/software-download/windows10
# • Windows 11: microsoft.com/software-download/windows11
# -> Créer ISO avec Media Creation Tool
# -> Licence Windows requise pour activation

# Vérifier intégrité ISO:
sha256sum ubuntu-22.04.3-live-server-amd64.iso
# Comparer avec SHA256 officiel


# PLANIFIER RESSOURCES VM:
# ═══════════════════════

# Ubuntu Server minimal:
# • vCPUs: 1-2
# • RAM: 2GB
# • Disque: 10GB
# • Réseau: NAT ou Bridged

# Ubuntu Desktop:
# • vCPUs: 2-4
# • RAM: 4GB
# • Disque: 25GB
# • Réseau: NAT ou Bridged

# Windows 10/11:
# • vCPUs: 2-4
# • RAM: 4-8GB
# • Disque: 40-60GB
# • Réseau: NAT ou Bridged


# ═══ 5.2 CRÉER VM AVEC ASSISTANT ═══

# LANCER ASSISTANT:
# ════════════════

# Méthode 1: Menu
# File -> Create a New Virtual Machine

# Méthode 2: Bouton
# [Create a New Virtual Machine] (écran accueil)

# Méthode 3: Raccourci
# Ctrl+N


# ASSISTANT CRÉATION VM:
# ═════════════════════

# Écran 1: Welcome
# ───────────────
# Choose installation method:
# 
# [WHITE_CIRCLE] Installer disc:
#   -> Utiliser CD/DVD physique (rare)
# 
# [WHITE_CIRCLE] Installer disc image file (iso):
#   -> Utiliser fichier ISO (RECOMMANDÉ)
#   [Browse] -> Sélectionner ubuntu-22.04.3-live-server-amd64.iso
# 
# [WHITE_CIRCLE] I will install the operating system later
#   -> Créer VM vide, installer OS manuellement après
# 
# [Next]


# Écran 2: Guest Operating System
# ───────────────────────────────
# Si ISO reconnu automatiquement:
# "Easy Install Information" s'affiche
# 
# Sinon, sélectionner manuellement:
# Guest operating system:
# [WHITE_CIRCLE] Linux
# [WHITE_CIRCLE] Windows
# [WHITE_CIRCLE] Other
# 
# Version: Ubuntu 64-bit
# (Liste déroulante avec toutes versions)
# 
# [Next]


# Écran 3: Name and Location
# ──────────────────────────
# Virtual machine name: Ubuntu-Server
# -> Nom affiché dans VMware
# -> Sans caractères spéciaux
# 
# Location: /home/user/vmware/Ubuntu-Server
# -> Dossier où VM sera sauvegardée
# [Browse] pour changer
# 
# Recommandations nommage:
# [OK] Ubuntu-Server-22.04
# [OK] Win10-Development
# [OK] Kali-PenTest
# [X] VM1 (pas descriptif)
# [X] Test (trop générique)
# 
# [Next]


# Écran 4: Specify Disk Capacity
# ──────────────────────────────
# Maximum disk size (GB): 20
# -> Taille disque virtuel
# 
# Recommandations:
# • Ubuntu Server minimal: 10-20GB
# • Ubuntu Desktop: 25-50GB
# • Windows 10: 40-60GB
# • CentOS: 20-30GB
# 
# Storage options:
# [WHITE_CIRCLE] Store virtual disk as a single file
#   -> 1 fichier .vmdk (plus rapide)
#   -> Recommandé SSD
# 
# [WHITE_CIRCLE] Split virtual disk into multiple files
#   -> Plusieurs fichiers 2GB (compatible anciennes versions)
#   -> Recommandé HDD ou compatibilité
# 
# [Next]


# Écran 5: Ready to Create
# ───────────────────────
# Summary de configuration:
# Name: Ubuntu-Server
# Location: /home/user/vmware/Ubuntu-Server
# OS: Linux Ubuntu 64-bit
# Hard Disk: 20GB
# Memory: 2GB (défaut)
# Network: NAT (défaut)
# 
# Options:
# [Customize Hardware] -> Modifier config avant création
# [x] Power on this virtual machine after creation
#   -> Démarrer VM automatiquement
# 
# [Finish]


# PERSONNALISER HARDWARE (OPTIONNEL):
# ══════════════════════════════════

# Si cliquez [Customize Hardware]:

# Memory:
# ──────
# Slider: 2GB -> 4GB (pour Ubuntu Desktop)

# Processors:
# ──────────
# Number of processors: 1
# Number of cores: 2
# -> Total: 2 vCPUs

# CD/DVD (IDE):
# ────────────
# [x] Connect at power on
# [WHITE_CIRCLE] Use ISO image file: ubuntu-22.04.3-live-server-amd64.iso
# [Browse] si besoin changer ISO

# Network Adapter:
# ───────────────
# Network connection:
# [WHITE_CIRCLE] Bridged (accès réseau direct)
# [WHITE_CIRCLE] NAT (derrière routeur) [DÉFAUT]
# [WHITE_CIRCLE] Host-only (réseau privé)

# Sound Card:
# ──────────
# [ ] Remove (économise ressources si serveur)

# USB Controller:
# ──────────────
# [x] Present
# USB 3.1 (recommandé)

# Display:
# ───────
# [x] Accelerate 3D graphics
# Graphics memory: 512MB

# [Close] -> Retour à écran Ready to Create
# [Finish] -> Créer VM


# ═══ 5.3 INSTALLER UBUNTU SERVER 22.04 ═══

# DÉMARRER INSTALLATION:
# ═════════════════════

# VM démarre automatiquement si coché
# Sinon: Cliquer [[BLACK_RIGHT-POINTING_TRIANGLE] Power On]

# GRUB boot menu s'affiche:
# *Try or Install Ubuntu Server
#  Ubuntu Server (safe graphics)
#  Test memory
# 
# Sélectionner première option (Enter)


# ÉCRANS INSTALLATION UBUNTU SERVER:
# ═════════════════════════════════

# 1. Language
# ──────────
# English [default]
# (Flèche bas/haut pour naviguer)
# [Done]

# 2. Keyboard configuration
# ────────────────────────
# Layout: French (ou English)
# Variant: French (ou English US)
# [Done]

# 3. Type of install
# ─────────────────
# [WHITE_CIRCLE] Ubuntu Server (default, minimal)
# [WHITE_CIRCLE] Ubuntu Server (minimized)
# [Done]

# 4. Network connections
# ─────────────────────
# Affiche interfaces réseau:
# ens33: DHCPv4 192.168.100.10/24
#        (adresse IP automatique via DHCP)
# 
# Configuration automatique OK [OK]
# [Done]

# 5. Configure proxy
# ─────────────────
# Proxy address: (vide si pas de proxy)
# [Done]

# 6. Mirror address
# ────────────────
# Archive mirror: http://archive.ubuntu.com/ubuntu
# (Miroir téléchargement packages)
# [Done] (laisser défaut)

# 7. Guided storage configuration
# ──────────────────────────────
# [x] Use an entire disk
# (Utiliser tout le disque virtuel)
# 
# [ ] Set up this disk as an LVM group
# (LVM = Logical Volume Manager, optionnel)
# 
# Choose disk: VBOX HARDDISK 20.000G
# [Done]

# 8. Storage configuration confirmation
# ────────────────────────────────────
# Partition scheme:
# PARTITION  SIZE    TYPE      MOUNTPOINT
# /dev/sda1  1M      BIOS boot
# /dev/sda2  18.99G  ext4      /
# 
# [Done]
# 
# Confirm destructive action:
# [Continue] (confirmer formatage)

# 9. Profile setup
# ───────────────
# Your name: John Doe
# Your server's name: ubuntu-server
# Pick a username: john
# Choose a password: ********
# Confirm password: ********
# 
# Recommandations:
# • Username: Lettres minuscules, pas espaces
# • Password: Min 8 caractères, fort
# 
# [Done]

# 10. SSH Setup
# ────────────
# [x] Install OpenSSH server
# -> Permet connexion SSH distance
# -> RECOMMANDÉ: Cocher
# 
# Import SSH identity: No
# [Done]

# 11. Featured Server Snaps
# ────────────────────────
# Liste de packages optionnels:
# [ ] docker
# [ ] microk8s
# [ ] nextcloud
# 
# (Ne rien cocher pour install minimale)
# [Done]

# INSTALLATION EN COURS:
# ─────────────────────
# Installation démarre:
# • Partitioning disks
# • Installing system
# • Installing packages
# • Configuring system
# 
# Durée: 5-15 minutes (selon CPU/disque)
# 
# [Reboot Now] apparaît quand terminé


# POST-INSTALLATION:
# ═════════════════

# 1. Retirer ISO:
# VM -> Settings -> CD/DVD
# [WHITE_CIRCLE] Use physical drive
# [OK]

# 2. Redémarrer:
# [Reboot Now]

# 3. Login:
# ubuntu-server login: john
# Password: ********

# 4. Vérifications:
# Hostname:
hostnamectl
# Static hostname: ubuntu-server

# Adresse IP:
ip addr show
# inet 192.168.100.10/24

# Connexion Internet:
ping -c 3 google.com
# 3 packets transmitted, 3 received [OK]

# 5. Mise à jour système:
sudo apt update
sudo apt upgrade -y

# 6. Installer VMware Tools:
sudo apt install -y open-vm-tools


# ═══ 5.4 INSTALLER UBUNTU DESKTOP 22.04 ═══

# DIFFÉRENCES AVEC SERVER:
# ═══════════════════════

# ISO: ubuntu-22.04.3-desktop-amd64.iso
# RAM recommandée: 4GB
# Disque: 25GB minimum
# Interface: Graphique (GNOME)


# INSTALLATION UBUNTU DESKTOP:
# ═══════════════════════════

# 1. Boot ISO
# ──────────
# GRUB menu:
# *Try or Install Ubuntu
# -> Enter

# 2. Welcome (après chargement live)
# ─────────────────────────────────
# Language: English
# [Install Ubuntu]

# 3. Keyboard layout
# ─────────────────
# Layout: French
# [Continue]

# 4. Updates and other software
# ────────────────────────────
# What apps would you like to install?
# [WHITE_CIRCLE] Normal installation (recommended)
# [WHITE_CIRCLE] Minimal installation
# 
# Other options:
# [x] Download updates while installing Ubuntu
# [x] Install third-party software
#   (drivers WiFi, graphiques, etc.)
# 
# [Continue]

# 5. Installation type
# ───────────────────
# [WHITE_CIRCLE] Erase disk and install Ubuntu
#   -> Utiliser tout disque (safe dans VM)
# 
# [ ] Encrypt the new Ubuntu installation
# [ ] Use LVM with the new Ubuntu installation
# 
# [Install Now]
# 
# Confirmation popup:
# [Continue]

# 6. Where are you?
# ────────────────
# Timezone: (auto-détecté depuis IP)
# Paris, France (UTC+1)
# [Continue]

# 7. Who are you?
# ──────────────
# Your name: John Doe
# Computer's name: ubuntu-desktop
# Username: john
# Password: ********
# Confirm: ********
# 
# [WHITE_CIRCLE] Require password to log in (sécurisé)
# [WHITE_CIRCLE] Log in automatically (pratique VM test)
# 
# [Continue]

# INSTALLATION EN COURS:
# ─────────────────────
# Slideshow pendant installation:
# • Welcome to Ubuntu
# • Browse the web
# • Office applications
# • Gaming on Ubuntu
# 
# Durée: 10-20 minutes

# Installation complete!
# [Restart Now]

# POST-INSTALLATION:
# ═════════════════

# 1. Retirer ISO (comme Server)

# 2. Reboot et login

# 3. Initial setup wizard:
# • Online Accounts (Skip)
# • Livepatch (Skip ou Enable)
# • Help improve Ubuntu (choice)
# • Privacy location (Off recommandé VM)
# • Ready to go! [Done]

# 4. Installer VMware Tools:
sudo apt install -y open-vm-tools-desktop

# 5. Redémarrer:
sudo reboot

# 6. Vérifier résolution dynamique:
# Redimensionner fenêtre VMware
# -> Résolution Ubuntu s'adapte [OK]


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 6: GESTION DES MACHINES VIRTUELLES
# ═══════════════════════════════════════════════════════════════════


# ═══ 6.1 OPÉRATIONS DE BASE VM ═══

# DÉMARRER VM:
# ═══════════

# Méthode 1: Interface
# Sélectionner VM dans liste
# [[BLACK_RIGHT-POINTING_TRIANGLE] Power On]

# Méthode 2: Raccourci
# Ctrl+B

# Méthode 3: CLI
vmrun start ~/vmware/Ubuntu-Server/Ubuntu-Server.vmx

# Options boot:
# • Power On
# • Power On to Firmware (EFI/BIOS)
# • Power On to Firmware (Setup)


# ARRÊTER VM:
# ══════════

# GRACEFUL SHUTDOWN (Recommandé):
# ──────────────────────────────
# VM -> Power -> Shut Down Guest
# -> Envoie signal shutdown au guest OS
# -> OS s'éteint proprement
# -> Fermeture applications, sync disques

# HARD POWER OFF:
# ──────────────
# VM -> Power -> Power Off
# -> Coupe alimentation immédiatement
# -> Comme débrancher PC
# [ATTENTION] Risque corruption données

# CLI:
# Graceful:
vmrun stop ~/vmware/Ubuntu/Ubuntu.vmx soft

# Hard:
vmrun stop ~/vmware/Ubuntu/Ubuntu.vmx hard


# SUSPENDRE VM:
# ════════════

# VM -> Power -> Suspend Guest
# -> Sauvegarde état RAM dans .vmem
# -> Libère ressources host
# -> Reprise ultra-rapide

# Différence Suspend vs Shutdown:
# • Suspend: État figé, reprise exacte
# • Shutdown: OS éteint, reboot normal

# Usage:
# • Suspend: Tests rapides, économie ressources
# • Shutdown: Arrêt prolongé, libération complète


# REDÉMARRER VM:
# ═════════════

# VM -> Power -> Restart Guest
# -> Reboot graceful (comme sudo reboot)

# VM -> Power -> Reset
# -> Reboot hard (comme bouton reset)


# PAUSE VM:
# ════════

# VM -> Power -> Pause
# -> Fige VM temporairement
# -> RAM reste allouée
# -> Rarement utilisé


# ═══ 6.2 SNAPSHOTS - SAUVEGARDES INSTANTANÉES ═══

# POURQUOI LES SNAPSHOTS?
# ═══════════════════════

# Problème sans snapshot:
# ──────────────────────
# Vous testez nouvelle config sur VM:
# 1. Modifier fichiers système
# 2. Installer packages
# 3. PROBLÈME! VM casse
# 4. Pas de retour arrière facile
# -> Réinstaller OS [WHITE_FROWNING_FACE]

# Solution avec snapshot:
# ──────────────────────
# 1. Prendre snapshot "Avant test"
# 2. Faire modifications
# 3. Si problème -> Restaurer snapshot
# 4. VM revient état "Avant test" [OK]


# CRÉER SNAPSHOT:
# ══════════════

# VM -> Snapshot -> Take Snapshot
# 
# Snapshot Name: Avant-MiseAJour-Kernel
# Description: Système stable avant update kernel 5.15
# 
# [x] Snapshot the virtual machine's memory
# -> Inclure état RAM (VM continue tourner)
# -> Si décoché: VM pause pendant snapshot
# 
# [Take Snapshot]

# Snapshot créé en quelques secondes!


# RESTAURER SNAPSHOT:
# ══════════════════

# VM -> Snapshot -> Revert to Snapshot
# -> VM revient dernier snapshot
# 
# Ou:
# VM -> Snapshot -> Snapshot Manager
# Sélectionner snapshot dans liste
# [Go To]


# SNAPSHOT MANAGER:
# ════════════════

# VM -> Snapshot -> Snapshot Manager
# 
# Affiche arbre snapshots:
# 
# You Are Here (état actuel)
#     ^
# Snapshot-3 (01/15/2024 14:30)
#     ^
# Snapshot-2 (01/15/2024 10:00)
#     ^
# Snapshot-1 (01/14/2024 16:00)
# 
# Actions:
# [Go To] -> Restaurer snapshot sélectionné
# [Delete] -> Supprimer snapshot
# [Delete All] -> Supprimer tous snapshots


# BONNES PRATIQUES SNAPSHOTS:
# ═══════════════════════════

# [OK] Nommer descriptif:
# [OK] Avant-Install-Apache
# [OK] Systeme-Propre-Post-Install
# [X] Snapshot1 (pas informatif)
# [X] Test (trop vague)

# [OK] Ajouter description:
# "Ubuntu 22.04 fraîchement installé, MAJ appliquées, 
#  aucune config custom. Point restauration propre."

# [OK] Prendre snapshot AVANT:
# • Installation logiciel
# • Configuration système
# • Mise à jour majeure
# • Test dangereux

# [OK] Supprimer vieux snapshots:
# • Snapshots consomment espace disque
# • Garder seulement snapshots utiles
# • Ex: Garder "Install propre" + "Config actuelle"

# [ATTENTION] Limitations:
# • Snapshots ralentissent performances
# • Accumulation snapshots = espace disque
# • Max recommandé: 3-5 snapshots par VM


# ═══ 6.3 CLONES - DUPLIQUER VMs ═══

# POURQUOI CLONER?
# ═══════════════

# Cas d'usage:
# • Créer environnement test identique à prod
# • Dupliquer VM pour autre projet
# • Distribuer VM préconfigurée (formation)
# • Créer cluster (ex: 3 nodes Kubernetes)


# TYPES DE CLONES:
# ═══════════════

# FULL CLONE (Clone complet):
# ──────────────────────────
# Copie complète et indépendante
# 
# VM Originale: Ubuntu.vmdk (20GB)
#     v Clone
# VM Clonée: Ubuntu-Clone.vmdk (20GB)
# 
# Avantages:
# [OK] Totalement indépendant
# [OK] Peut supprimer original
# [OK] Performances identiques original
# 
# Inconvénients:
# [X] Prend beaucoup d'espace (2× taille VM)
# [X] Clone prend du temps (copie 20GB)

# LINKED CLONE (Clone lié):
# ────────────────────────
# Dépend VM parent via snapshot
# 
# VM Originale: Ubuntu.vmdk (20GB)
#     v Snapshot
# Snapshot: Ubuntu-Snapshot.vmdk
#     v Linked Clone
# VM Clonée: Ubuntu-Clone.vmdk (2GB seulement!)
#              -> Pointe vers Snapshot parent
# 
# Avantages:
# [OK] Clone ultra-rapide (secondes)
# [OK] Économie espace (partage disque parent)
# [OK] Parfait tests multiples
# 
# Inconvénients:
# [X] Dépend VM parent (ne peut pas supprimer)
# [X] Performance légèrement réduite
# [X] Si parent corrompu -> Clone corrompu


# CRÉER CLONE:
# ═══════════

# Prérequis: VM doit être éteinte

# VM -> Manage -> Clone
# 
# Écran 1: Clone from
# ───────────────────
# Clone from:
# [WHITE_CIRCLE] The current state
# [WHITE_CIRCLE] An existing snapshot
# 
# [Next]

# Écran 2: Clone type
# ──────────────────
# [WHITE_CIRCLE] Create a full clone
# [WHITE_CIRCLE] Create a linked clone
# 
# [Next]

# Écran 3: Name and location
# ─────────────────────────
# Name: Ubuntu-Clone
# Location: /home/user/vmware/Ubuntu-Clone
# 
# [Finish]

# Clone création en cours...
# Full clone: 5-15 minutes
# Linked clone: <1 minute


# POST-CLONE CONFIGURATION:
# ════════════════════════

# [ATTENTION] IMPORTANT: Changer identifiants!

# 1. Hostname:
sudo hostnamectl set-hostname ubuntu-clone

# 2. Machine ID:
sudo rm /etc/machine-id
sudo dbus-uuidgen --ensure=/etc/machine-id

# 3. SSH keys (si SSH server):
sudo rm /etc/ssh/ssh_host_*
sudo dpkg-reconfigure openssh-server

# 4. Network (si Bridged et IPs statiques):
# Changer IP pour éviter conflit
sudo nano /etc/netplan/00-installer-config.yaml
# Modifier adresses:
# addresses: [192.168.1.101/24]  # Au lieu de .100

# 5. Reboot:
sudo reboot


# ═══ 6.4 EXPORT / IMPORT - OVF/OVA ═══

# POURQUOI EXPORTER?
# ═════════════════

# • Partager VM avec collègues
# • Backup VM
# • Migrer VM vers autre host
# • Distribuer environnement préconfigré
# • Migration ESXi <-> Workstation


# FORMATS EXPORT:
# ══════════════

# OVF (Open Virtualization Format):
# ─────────────────────────────────
# Standard ouvert, multi-fichiers
# 
# Contenu:
# • .ovf (XML configuration)
# • .vmdk (disques virtuels)
# • .mf (manifest, checksums)
# 
# Exemple:
# Ubuntu-Export/
# ├── Ubuntu.ovf
# ├── Ubuntu-disk1.vmdk
# └── Ubuntu.mf

# OVA (Open Virtualization Archive):
# ──────────────────────────────────
# Archive unique (OVF + VMDKs)
# 
# Exemple:
# Ubuntu-Export.ova (fichier unique)
# 
# Avantages:
# [OK] Plus facile partager (1 fichier)
# [OK] Plus petit (compression)


# EXPORTER VM:
# ═══════════

# Prérequis: VM doit être éteinte

# File -> Export to OVF
# 
# Écran 1: Source
# ──────────────
# Virtual machine: Ubuntu-Server
# [Next]

# Écran 2: Destination
# ───────────────────
# Directory: /home/user/Exports/Ubuntu-Server
# 
# Name: Ubuntu-Server
# 
# Format:
# [WHITE_CIRCLE] OVF (folder of files)
# [WHITE_CIRCLE] OVA (single file) [RECOMMANDÉ]
# 
# Description: (optionnel)
# Ubuntu Server 22.04 LTS
# Configured with Apache, MySQL, PHP
# Username: ubuntu, Password: ubuntu123
# 
# [x] Include extra configuration information
# [x] Include image files (ISOs)
# 
# [Export]

# Export en cours...
# Durée: 5-20 minutes (selon taille VM)
# 
# Fichier créé:
# /home/user/Exports/Ubuntu-Server.ova


# IMPORTER VM:
# ═══════════

# File -> Open
# Naviguer vers fichier .ova ou .ovf
# Sélectionner Ubuntu-Server.ova
# [Open]

# Écran: Import Virtual Machine
# ────────────────────────────
# Name: Ubuntu-Server-Imported
# Location: /home/user/vmware/Ubuntu-Server-Imported
# 
# Storage:
# [WHITE_CIRCLE] Store virtual disk as a single file
# [WHITE_CIRCLE] Split virtual disk into multiple files
# 
# [Import]

# Import en cours...
# VM apparaît dans Library [OK]


# COMPATIBILITÉ OVF/OVA:
# ═════════════════════

# Compatible avec:
# [OK] VMware Workstation
# [OK] VMware Player
# [OK] VMware Fusion
# [OK] VMware ESXi
# [OK] VMware vSphere
# [OK] VirtualBox (avec limitations)

# Limitations VirtualBox:
# • Peut nécessiter réinstaller Guest Additions
# • Certaines configs réseau à reconfigurer
# • Performances variables


# ═══ 6.5 GESTION MULTI-VMs ═══

# TEAMS (Workstation Pro uniquement):
# ══════════════════════════════════

# Team = Groupe de VMs liées
# Permet gérer plusieurs VMs comme une unité

# Créer Team:
# ──────────
# File -> New Team
# 
# Ajouter VMs existantes ou nouvelles:
# • Ubuntu-Web (Apache)
# • Ubuntu-DB (MySQL)
# • Ubuntu-App (Backend)
# 
# Configuration Team:
# • LAN Segment: Réseau privé Team
# • Start/Stop toutes VMs ensemble
# • Snapshot de tout le Team

# Cas d'usage:
# • Architecture 3-tiers (Web-App-DB)
# • Cluster Kubernetes (3 nodes)
# • Infrastructure test complète


# GESTION BIBLIOTHÈQUE VMs:
# ════════════════════════

# Organisation:
# ────────────
# ~/vmware/
# ├── Production/
# │   ├── Web-Server/
# │   └── Database/
# ├── Development/
# │   ├── Dev-Ubuntu/
# │   └── Dev-CentOS/
# ├── Testing/
# │   ├── Test-Win10/
# │   └── Test-Kali/
# └── Templates/
#     ├── Ubuntu-22.04-Template/
#     └── Windows-Server-Template/

# Favorites:
# ─────────
# Clic droit VM -> Add to Favorites
# -> Accès rapide VMs fréquentes


# ═══ 6.6 PERFORMANCES ET OPTIMISATION ═══

# ALLOCATION RESSOURCES OPTIMALE:
# ═══════════════════════════════

# CPU:
# ───
# Règle: 1 vCPU par cœur physique
# Éviter overcommit >2:1
# 
# Host: 8 cœurs
# [OK] VM1: 2 vCPUs, VM2: 4 vCPUs, VM3: 2 vCPUs (total: 8)
# [OK] VM1-4: 4 vCPUs chacune (total: 16, ratio 2:1)
# [X] VM1-5: 8 vCPUs chacune (total: 40, ratio 5:1)

# RAM:
# ───
# Règle: Éviter overcommit RAM
# Laisser 25% RAM libre pour host
# 
# Host: 16GB
# [OK] Total VMs: 12GB (4GB libre)
# [ATTENTION] Total VMs: 14GB (2GB libre, limite)
# [X] Total VMs: 18GB (swapping!)

# Disque:
# ──────
# • Préférer SSD/NVMe (10× plus rapide HDD)
# • Thick Provisioned Eager Zeroed: Performance max
# • Thin Provisioned: Économie espace

# Réseau:
# ──────
# • Bridged: Performance max (accès direct carte)
# • NAT: Performance réduite (NAT overhead)


# DÉSACTIVER SERVICES INUTILES:
# ════════════════════════════

# Dans VM:
# ───────
# Si serveur sans GUI:
# • Désactiver services graphiques
# • Pas d'effets desktop (composition)
# • Terminal seulement

# VM Settings:
# ───────────
# Hardware non utilisé:
# • Sound Card -> Remove (si serveur)
# • USB Controller -> Remove (si pas besoin)
# • Printer -> Remove


# VMWARE TOOLS OPTIMISATION:
# ═════════════════════════

# Memory ballooning:
# ─────────────────
# Permet récupérer RAM non utilisée
# Activé par défaut avec VMware Tools

# Time synchronization:
# ────────────────────
# Désactiver si VM a NTP:
# VM -> Settings -> Options -> VMware Tools
# [ ] Synchronize guest time with host


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 3: CRÉATION ET GESTION DE MACHINES VIRTUELLES
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 3:
# 
# [OK] Préparation installation (télécharger ISOs, planifier ressources)
# [OK] Créer VM avec assistant (étapes détaillées)
# [OK] Installer Ubuntu Server 22.04 (installation complète)
# [OK] Installer Ubuntu Desktop 22.04 (différences avec Server)
# [OK] Opérations base VM (Start, Stop, Suspend, Restart, Reset, Pause)
# [OK] Snapshots (créer, restaurer, manager, bonnes pratiques)
# [OK] Clones (Full Clone vs Linked Clone, post-clone config)
# [OK] Export/Import OVF/OVA (partage, backup, migration)
# [OK] Gestion multi-VMs (Teams, organisation bibliothèque)
# [OK] Optimisation performances (CPU, RAM, Disque, Réseau)
# 
# [OBJECTIF] PROCHAINE PARTIE:
# Partie 4 couvre Réseaux Virtuels en profondeur
# (Types réseau, Configuration, VLANs, Routage, Troubleshooting)
# 
# --- FIN PARTIE 3 ---

# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 4: RÉSEAUX VIRTUELS
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 7: CONCEPTS RÉSEAUX VIRTUALISATION
# ═══════════════════════════════════════════════════════════════════


# ═══ 7.1 ARCHITECTURE RÉSEAU VMWARE ═══

# COMPOSANTS RÉSEAU VIRTUELS:
# ═══════════════════════════

# vNIC (Virtual Network Interface Card):
# ──────────────────────────────────────
# Carte réseau virtuelle dans VM
# Se comporte comme carte Ethernet physique
# Adresse MAC unique générée automatiquement
# 
# VM peut avoir plusieurs vNICs:
# • eth0 (vNIC1) -> Internet (NAT)
# • eth1 (vNIC2) -> Réseau interne (Host-Only)

# vSwitch (Virtual Switch):
# ────────────────────────
# Switch réseau logiciel
# Connecte VMs entre elles et au réseau physique
# 
# Types:
# • VMnet0: Bridged (pont vers carte physique)
# • VMnet1: Host-Only (réseau privé)
# • VMnet8: NAT (routeur virtuel)

# VMNIC (Physical Network Adapter):
# ─────────────────────────────────
# Carte réseau physique du host
# Ex: eth0, wlan0
# Uplink vers réseau externe


# FLUX RÉSEAU TYPIQUE:
# ═══════════════════

# VM -> Internet (NAT):
# ───────────────────
# 
# [VM Ubuntu]
#     v vNIC (192.168.100.10)
# [vSwitch VMnet8]
#     v Virtual NAT Router (192.168.100.2)
# [VMNIC eth0] (192.168.1.50 sur réseau physique)
#     v
# [Router Physique] -> Internet
# 
# Traduction NAT:
# VM 192.168.100.10:5000 -> Host 192.168.1.50:5000 -> Internet


# ═══ 7.2 MODE BRIDGED (PONT) ═══

# CONCEPT:
# ═══════

# VM directement sur réseau physique
# Comme si VM = ordinateur physique sur réseau
# 
# ┌─────────────────────────────────────────────┐
# │           Réseau Physique 192.168.1.0/24    │
# │                                             │
# │  [Router]  [PC1]  [PC2]  [Host]  [VM]      │
# │   .1       .10    .20    .50     .51       │
# └─────────────────────────────────────────────┘
# 
# VM obtient IP du même DHCP que host
# VM accessible depuis autres machines réseau


# CONFIGURATION:
# ═════════════

# VM -> Settings -> Network Adapter
# Network connection:
# [WHITE_CIRCLE] Bridged: Connected directly to the physical network
# 
# Bridged to: Automatic
# (Ou sélectionner carte spécifique)
# [x] Replicate physical network connection state


# DANS LA VM (Ubuntu):
# ═══════════════════

# Vérifier IP:
ip addr show ens33
# inet 192.168.1.51/24
# -> IP dans même sous-réseau que host!

# Vérifier gateway:
ip route show
# default via 192.168.1.1 dev ens33
# -> Même gateway que host

# Tester connectivité:
# Ping host:
ping 192.168.1.50

# Ping autre PC réseau:
ping 192.168.1.20

# Internet:
ping 8.8.8.8


# QUAND UTILISER BRIDGED:
# ══════════════════════

# [OK] VM doit être accessible depuis réseau
# [OK] Serveur web/SSH accessible
# [OK] VM = machine à part entière
# [OK] Tests réseau réalistes
# 
# [X] Mobilité (laptop change réseau)
# [X] Sécurité (VM exposée directement)
# [X] DHCP peut manquer d'IPs


# AVANTAGES:
# ═════════
# [OK] Performance max (pas NAT)
# [OK] Accès direct depuis réseau
# [OK] Serveurs accessibles

# INCONVÉNIENTS:
# ═════════════
# [X] VM exposée au réseau
# [X] Consomme IP réseau
# [X] Problèmes si laptop mobile


# ═══ 7.3 MODE NAT (NETWORK ADDRESS TRANSLATION) ═══

# CONCEPT:
# ═══════

# VM derrière routeur virtuel
# NAT traduit IPs VM <-> Host
# 
# ┌──────────────────────────────────┐
# │         Host (192.168.1.50)      │
# │                                  │
# │  ┌──────────────────────────┐   │
# │  │   Réseau VMnet8          │   │
# │  │   192.168.100.0/24       │   │
# │  │                          │   │
# │  │  [VM1]     [VM2]    [VM3]│   │
# │  │  .10       .11      .12  │   │
# │  └──────────────────────────┘   │
# │           v                      │
# │    [NAT Router .2]               │
# │           v                      │
# └───────────────────────────────────┘
#             v
#    Réseau Physique -> Internet
# 
# VMs accèdent Internet via host
# VMs invisibles depuis réseau externe


# CONFIGURATION:
# ═════════════

# VM -> Settings -> Network Adapter
# Network connection:
# [WHITE_CIRCLE] NAT: Used to share the host's IP address


# DANS LA VM:
# ══════════

# IP automatique (DHCP VMnet8):
ip addr show ens33
# inet 192.168.100.10/24

# Gateway = NAT router:
ip route show
# default via 192.168.100.2 dev ens33

# DNS fourni par VMware:
cat /etc/resolv.conf
# nameserver 192.168.100.2

# Tests:
# Internet OK:
ping 8.8.8.8 [OK]

# Host accessible:
ping 192.168.100.1 [OK]

# Autre VM VMnet8:
ping 192.168.100.11 [OK]

# Autre PC réseau:
ping 192.168.1.20 [X]
# -> Pas accessible (NAT unidirectionnel)


# PORT FORWARDING (Accès VM depuis extérieur):
# ════════════════════════════════════════════

# Problème: VM derrière NAT = inaccessible
# Solution: Redirection de ports

# Virtual Network Editor -> VMnet8 -> NAT Settings
# 
# [Add] Port Forwarding:
# Host port: 8080
# Virtual machine IP: 192.168.100.10
# Virtual machine port: 80
# Description: Apache web server
# 
# Résultat:
# Host:8080 -> VM:80
# 
# Accès depuis navigateur host:
# http://localhost:8080
# -> Redirige vers Apache dans VM


# QUAND UTILISER NAT:
# ══════════════════

# [OK] Laptop mobile (WiFi change)
# [OK] VMs pas besoin accès externe
# [OK] Sécurité (VMs cachées)
# [OK] Économie IPs réseau
# [OK] Configuration simple

# AVANTAGES:
# ═════════
# [OK] VMs protégées (firewall NAT)
# [OK] Fonctionne partout (home, café, bureau)
# [OK] Pas d'IP réseau nécessaire

# INCONVÉNIENTS:
# ═════════════
# [X] VMs inaccessibles directement
# [X] Port forwarding pour serveurs
# [X] Légère overhead NAT


# ═══ 7.4 MODE HOST-ONLY ═══

# CONCEPT:
# ═══════

# Réseau privé Host <-> VMs
# Pas d'accès Internet
# Isolation totale
# 
# ┌──────────────────────────────────┐
# │         Host                     │
# │   Interface: vmnet1              │
# │   IP: 192.168.1.1               │
# │                                  │
# │  ┌──────────────────────────┐   │
# │  │   Réseau VMnet1          │   │
# │  │   192.168.1.0/24        │   │
# │  │                          │   │
# │  │  [VM1]     [VM2]    [VM3]│   │
# │  │  .10       .11      .12  │   │
# │  └──────────────────────────┘   │
# └──────────────────────────────────┘
# 
# [OK] Host <-> VMs: Communiquent
# [OK] VM1 <-> VM2: Communiquent
# [X] Internet: Pas d'accès
# [X] Réseau physique: Invisible


# CONFIGURATION:
# ═════════════

# VM -> Settings -> Network Adapter
# Network connection:
# [WHITE_CIRCLE] Host-only: A private network shared with the host


# DANS LA VM:
# ══════════

# IP automatique (DHCP VMnet1):
ip addr show ens33
# inet 192.168.1.10/24

# Pas de gateway par défaut:
ip route show
# 192.168.1.0/24 dev ens33 proto kernel scope link
# -> Pas de route Internet

# Tests:
# Host accessible:
ping 192.168.1.1 [OK]

# Autre VM VMnet1:
ping 192.168.1.11 [OK]

# Internet:
ping 8.8.8.8 [X]
# -> Pas d'accès (attendu)


# QUAND UTILISER HOST-ONLY:
# ═════════════════════════

# [OK] Tests sécurité (malware analysis)
# [OK] Lab isolé (pentesting)
# [OK] Développement sans Internet
# [OK] Cluster VMs communicant entre elles

# AVANTAGES:
# ═════════
# [OK] Isolation maximale
# [OK] Sécurité (pas de fuites)
# [OK] Lab contrôlé

# INCONVÉNIENTS:
# ═════════════
# [X] Pas d'Internet (sauf routage manuel)
# [X] Pas d'accès réseau physique


# AJOUTER INTERNET À HOST-ONLY (AVANCÉ):
# ══════════════════════════════════════

# Sur Host (Ubuntu):
# ─────────────────

# 1. Activer IP forwarding:
sudo sysctl -w net.ipv4.ip_forward=1

# Permanent:
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf

# 2. Configurer NAT (iptables):
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i vmnet1 -o eth0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o vmnet1 -m state --state RELATED,ESTABLISHED -j ACCEPT

# 3. Dans VM, ajouter route par défaut:
sudo ip route add default via 192.168.1.1

# Maintenant VM Host-Only a Internet! [OK]


# ═══ 7.5 MODE CUSTOM (VMnet2-9) ═══

# CRÉER RÉSEAU CUSTOM:
# ═══════════════════

# Virtual Network Editor -> [Add Network]
# Sélectionner VMnet disponible: VMnet2
# 
# Type:
# [WHITE_CIRCLE] Host-only
# Subnet IP: 10.0.0.0
# Subnet mask: 255.255.255.0
# 
# [x] Use local DHCP service
# DHCP range: 10.0.0.128 - 10.0.0.254
# 
# [Apply]


# CAS D'USAGE MULTI-RÉSEAUX:
# ═════════════════════════

# VM Firewall avec 3 interfaces:
# ──────────────────────────────
# 
# eth0: Bridged (WAN - Internet)
# eth1: VMnet2 (LAN - Interne)
# eth2: VMnet3 (DMZ - Serveurs publics)
# 
# ┌────────────────────────────────────┐
# │                                    │
# │  [Internet] <- eth0 (Bridged)       │
# │       v                            │
# │  [Firewall VM]                     │
# │       v         v                  │
# │     eth1      eth2                 │
# │   (VMnet2)  (VMnet3)               │
# │       v         v                  │
# │  [LAN VMs]  [DMZ VMs]              │
# │   (privées) (publics)              │
# └────────────────────────────────────┘


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 8: CONFIGURATION RÉSEAU AVANCÉE
# ═══════════════════════════════════════════════════════════════════


# ═══ 8.1 CONFIGURATION IP STATIQUE ═══

# UBUNTU NETPLAN (20.04+):
# ═══════════════════════

# Fichier config:
sudo nano /etc/netplan/00-installer-config.yaml

# Configuration DHCP (défaut):
network:
  ethernets:
    ens33:
      dhcp4: true
  version: 2

# Configuration IP STATIQUE:
network:
  ethernets:
    ens33:
      dhcp4: no
      addresses:
        - 192.168.100.50/24
      routes:
        - to: default
          via: 192.168.100.2
      nameservers:
        addresses:
          - 8.8.8.8
          - 8.8.4.4
  version: 2

# Appliquer:
sudo netplan apply

# Vérifier:
ip addr show ens33
# inet 192.168.100.50/24 [OK]


# ANCIENNES VERSIONS UBUNTU (/etc/network/interfaces):
# ═══════════════════════════════════════════════════

sudo nano /etc/network/interfaces

# IP Statique:
auto ens33
iface ens33 inet static
    address 192.168.100.50
    netmask 255.255.255.0
    gateway 192.168.100.2
    dns-nameservers 8.8.8.8 8.8.4.4

# Redémarrer réseau:
sudo systemctl restart networking


# ═══ 8.2 MULTI-HOMING (PLUSIEURS NICs) ═══

# AJOUTER 2ème vNIC:
# ═════════════════

# VM -> Settings -> Add -> Network Adapter
# 
# Adapter 1: NAT (Internet)
# Adapter 2: Host-Only (Réseau interne)


# CONFIGURATION NETPLAN:
# ═════════════════════

network:
  ethernets:
    ens33:  # Adapter 1 - NAT
      dhcp4: true
    ens34:  # Adapter 2 - Host-Only
      dhcp4: no
      addresses:
        - 192.168.1.100/24
  version: 2

# Appliquer:
sudo netplan apply

# Vérifier:
ip addr show
# ens33: 192.168.100.10/24 (NAT)
# ens34: 192.168.1.100/24 (Host-Only)


# ROUTAGE MULTI-INTERFACES:
# ═════════════════════════

# Internet via ens33 (NAT):
ip route show
# default via 192.168.100.2 dev ens33

# Réseau 192.168.1.0/24 via ens34:
# (route automatique pour subnet local)


# ═══ 8.3 VLANs (802.1Q) ═══

# CONCEPT VLANs VIRTUELS:
# ══════════════════════

# Segmenter réseau logiquement
# 
# vSwitch avec VLANs:
# ┌───────────────────────────────────┐
# │     vSwitch (VMnet2)              │
# │                                   │
# │  VLAN 10    VLAN 20    VLAN 30   │
# │  (Dev)      (Test)     (Prod)    │
# │    v          v          v       │
# │  [VM1]     [VM2]     [VM3]       │
# └───────────────────────────────────┘
# 
# VMs différents VLANs ne communiquent pas
# (sauf routage inter-VLAN)


# CONFIGURER VLAN DANS VM:
# ═══════════════════════

# 1. Installer vlan package:
sudo apt install vlan

# 2. Charger module 8021q:
sudo modprobe 8021q
echo "8021q" | sudo tee -a /etc/modules

# 3. Créer interface VLAN (Netplan):
sudo nano /etc/netplan/00-installer-config.yaml

network:
  ethernets:
    ens33:
      dhcp4: no
  vlans:
    vlan10:
      id: 10
      link: ens33
      addresses:
        - 10.0.10.10/24
    vlan20:
      id: 20
      link: ens33
      addresses:
        - 10.0.20.10/24
  version: 2

# 4. Appliquer:
sudo netplan apply

# 5. Vérifier:
ip addr show
# ens33.10: 10.0.10.10/24 (VLAN 10)
# ens33.20: 10.0.20.10/24 (VLAN 20)


# ═══ 8.4 BONDING/TEAMING (LINK AGGREGATION) ═══

# CONCEPT:
# ═══════

# Combiner plusieurs NICs -> 1 interface logique
# 
# Modes:
# • Mode 0 (balance-rr): Round-robin, performance
# • Mode 1 (active-backup): Redondance
# • Mode 2 (balance-xor): XOR load balancing
# • Mode 3 (broadcast): Broadcast tous
# • Mode 4 (802.3ad/LACP): Dynamic aggregation


# CONFIGURATION BOND:
# ══════════════════

network:
  ethernets:
    ens33:
      dhcp4: no
    ens34:
      dhcp4: no
  bonds:
    bond0:
      interfaces:
        - ens33
        - ens34
      parameters:
        mode: active-backup
        primary: ens33
      addresses:
        - 192.168.100.100/24
      routes:
        - to: default
          via: 192.168.100.2
  version: 2

# Appliquer:
sudo netplan apply

# Vérifier:
cat /proc/net/bonding/bond0


# ═══ 8.5 DIAGNOSTICS RÉSEAU ═══

# OUTILS ESSENTIELS:
# ═════════════════

# ping: Test connectivité ICMP
ping -c 4 8.8.8.8

# traceroute: Tracer route paquets
traceroute google.com

# nslookup/dig: Résolution DNS
nslookup google.com
dig google.com

# netstat: Connexions actives
netstat -tuln

# ss: Socket statistics (moderne)
ss -tuln

# ip: Gestion interfaces (moderne)
ip addr show
ip route show
ip link show

# tcpdump: Capture paquets
sudo tcpdump -i ens33 icmp

# wireshark: Analyse paquets (GUI)
sudo apt install wireshark


# TROUBLESHOOTING RÉSEAU VM:
# ═════════════════════════

# Problème 1: Pas d'IP (DHCP fail)
# ────────────────────────────────
# Vérifier:
ip addr show ens33
# Si pas d'IP:

# Solution:
sudo dhclient ens33
# Ou:
sudo systemctl restart networking

# Problème 2: Pas d'accès Internet
# ────────────────────────────────
# Vérifier gateway:
ip route show
# default via X.X.X.X dev ens33

# Tester gateway:
ping <gateway_ip>

# Tester DNS:
ping 8.8.8.8  # OK?
ping google.com  # Fail? -> Problème DNS

# Vérifier DNS:
cat /etc/resolv.conf
# nameserver 8.8.8.8

# Problème 3: VM pas accessible depuis host
# ─────────────────────────────────────────
# Vérifier mode réseau:
# Si NAT -> Port forwarding nécessaire
# Si Bridged -> Vérifier firewall VM

# Vérifier firewall Ubuntu:
sudo ufw status
# Si active:
sudo ufw allow 22/tcp  # SSH
sudo ufw allow 80/tcp  # HTTP


# ═══ 8.6 SÉCURITÉ RÉSEAU ═══

# FIREWALL VM (UFW):
# ═════════════════

# Activer UFW:
sudo ufw enable

# Règles de base:
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Autoriser services:
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

# Autoriser IP spécifique:
sudo ufw allow from 192.168.1.50

# Status:
sudo ufw status verbose


# IPTABLES (Avancé):
# ═════════════════

# Bloquer tout entrant sauf established:
sudo iptables -P INPUT DROP
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -i lo -j ACCEPT

# Autoriser SSH:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Sauvegarder règles:
sudo iptables-save > /etc/iptables/rules.v4


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 4: RÉSEAUX VIRTUELS
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 4:
# 
# [OK] Architecture réseau VMware (vNIC, vSwitch, VMNIC)
# [OK] Mode Bridged (VM sur réseau physique direct)
# [OK] Mode NAT (VM derrière routeur virtuel, port forwarding)
# [OK] Mode Host-Only (réseau privé isolé)
# [OK] Mode Custom (VMnet2-9, réseaux custom)
# [OK] IP statique (Netplan Ubuntu)
# [OK] Multi-homing (plusieurs NICs par VM)
# [OK] VLANs 802.1Q (segmentation logique)
# [OK] Bonding/Teaming (agrégation liens)
# [OK] Diagnostics réseau (ping, traceroute, tcpdump)
# [OK] Troubleshooting (DHCP, Internet, DNS)
# [OK] Sécurité réseau (UFW, iptables)
# 
# [OBJECTIF] PROCHAINE PARTIE:
# Partie 5 couvre Stockage et Disques Virtuels
# (Types disques, Thin/Thick, Expansion, Snapshots disques, Performance)
# 
# --- FIN PARTIE 4 ---

# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 5: STOCKAGE ET DISQUES VIRTUELS
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 9: DISQUES VIRTUELS (VMDK)
# ═══════════════════════════════════════════════════════════════════


# ═══ 9.1 TYPES DE DISQUES VIRTUELS ═══

# THICK PROVISIONED (Pré-alloué):
# ═══════════════════════════════

# Thick Provisioned Lazy Zeroed:
# ──────────────────────────────
# Espace disque réservé immédiatement
# Zéros écrits à la demande (lazy)
# 
# Exemple: Disque 50GB
# Création: Réserve 50GB immédiatement
# Écriture données: Remplace zéros
# 
# Avantages:
# [OK] Performance bonne
# [OK] Espace garanti
# 
# Inconvénients:
# [X] Espace disque host utilisé immédiatement
# [X] Création lente (doit allouer 50GB)

# Thick Provisioned Eager Zeroed:
# ───────────────────────────────
# Espace réservé + tous zéros écrits immédiatement
# 
# Exemple: Disque 50GB
# Création: Réserve 50GB + écrit zéros partout
# 
# Avantages:
# [OK] Performance MAXIMALE
# [OK] Sécurité (pas de données précédentes)
# [OK] Recommandé production
# 
# Inconvénients:
# [X] Création TRÈS lente (écrire 50GB zéros)
# [X] Espace disque utilisé immédiatement


# THIN PROVISIONED (Allocation dynamique):
# ════════════════════════════════════════

# Espace alloué dynamiquement selon besoin
# 
# Exemple: Disque 50GB thin
# Création: Fichier .vmdk ~1MB
# VM utilise 10GB: Fichier .vmdk ~10GB
# VM utilise 30GB: Fichier .vmdk ~30GB
# 
# Avantages:
# [OK] Économie espace disque (seulement utilisé)
# [OK] Création ultra-rapide
# [OK] Overprovisioning possible
# 
# Inconvénients:
# [X] Performance réduite (allocation on-the-fly)
# [X] Risque saturation disque host
# [X] Fragmentation


# COMPARAISON TABLEAU:
# ═══════════════════

# ┌────────────────┬──────────┬──────────┬──────────┐
# │ Critère        │ Lazy Zero│Eager Zero│   Thin   │
# ├────────────────┼──────────┼──────────┼──────────┤
# │ Performance    │   ****  │  *****  │   ***   │
# │ Création rapide│   ***   │    *     │  *****  │
# │ Économie espace│    [X]     │    [X]     │    [OK]     │
# │ Sécurité       │   ***   │  *****  │   ***   │
# │ Production     │    OK    │ EXCELLENT│ Acceptable│
# │ Dev/Test       │    OK    │ Overkill │ PARFAIT  │
# └────────────────┴──────────┴──────────┴──────────┘


# CHOISIR TYPE DISQUE:
# ═══════════════════

# VM -> Settings -> Hard Disk -> Expand -> Disk Utilities
# Convert to: 
# [WHITE_CIRCLE] Thick Provisioned Lazy Zeroed
# [WHITE_CIRCLE] Thick Provisioned Eager Zeroed
# [WHITE_CIRCLE] Thin Provisioned


# ═══ 9.2 AJOUTER DISQUE VIRTUEL ═══

# CRÉER NOUVEAU DISQUE:
# ════════════════════

# VM -> Settings -> [Add] -> Hard Disk
# 
# Écran 1: Disk type
# ─────────────────
# Recommended disk type:
# [WHITE_CIRCLE] SCSI (Recommended)
# [WHITE_CIRCLE] SATA
# [WHITE_CIRCLE] NVMe
# [WHITE_CIRCLE] IDE
# 
# [Next]

# Écran 2: Disk
# ────────────
# [WHITE_CIRCLE] Create a new virtual disk
# [WHITE_CIRCLE] Use an existing virtual disk
# [WHITE_CIRCLE] Use a physical disk (for advanced users)
# 
# [Next]

# Écran 3: Disk Size
# ─────────────────
# Maximum disk size (GB): 20
# 
# Allocate disk space:
# [WHITE_CIRCLE] Allocate all disk space now (Thick Eager)
# [WHITE_CIRCLE] Store virtual disk as a single file (1 .vmdk)
# [WHITE_CIRCLE] Split virtual disk into multiple files (2GB chacun)
# 
# [Next]

# Écran 4: Disk File
# ─────────────────
# Disk file: Ubuntu-1.vmdk
# 
# [Finish]


# DANS LA VM UBUNTU:
# ═════════════════

# Nouveau disque détecté:
dmesg | grep sd
# [  2.345] sd 2:0:1:0: [sdb] 41943040 sectors
# -> Disque sdb ajouté

# Lister disques:
lsblk
# sda    20G (disque système)
# ├─sda1  1M
# └─sda2 20G
# sdb    20G (nouveau disque) <- NON PARTITIONNÉ


# PARTITIONNER DISQUE:
# ═══════════════════

# Méthode 1: fdisk (classique)
# ────────────────────────────
sudo fdisk /dev/sdb

# Commandes fdisk:
# n  -> Nouvelle partition
# p  -> Partition primaire
# 1  -> Numéro partition
# Enter -> Premier secteur (défaut)
# Enter -> Dernier secteur (tout le disque)
# w  -> Écrire et quitter

# Méthode 2: parted (moderne)
# ───────────────────────────
sudo parted /dev/sdb
# (parted) mklabel gpt
# (parted) mkpart primary ext4 0% 100%
# (parted) quit


# FORMATER PARTITION:
# ══════════════════

# Ext4 (Linux):
sudo mkfs.ext4 /dev/sdb1

# XFS (alternative):
sudo mkfs.xfs /dev/sdb1

# Vérifier:
lsblk -f
# sdb1  ext4  /dev/sdb1


# MONTER PARTITION:
# ════════════════

# Créer point de montage:
sudo mkdir /mnt/data

# Monter:
sudo mount /dev/sdb1 /mnt/data

# Vérifier:
df -h
# /dev/sdb1  20G  ... /mnt/data


# MONTAGE AUTOMATIQUE (fstab):
# ════════════════════════════

# Obtenir UUID partition:
sudo blkid /dev/sdb1
# UUID="abcd1234-..."

# Éditer fstab:
sudo nano /etc/fstab

# Ajouter ligne:
UUID=abcd1234-... /mnt/data ext4 defaults 0 2

# Tester:
sudo mount -a

# Vérifier après reboot:
sudo reboot
df -h | grep data
# /dev/sdb1  20G  ... /mnt/data [OK]


# ═══ 9.3 REDIMENSIONNER DISQUE ═══

# AGRANDIR DISQUE VMDK:
# ════════════════════

# [ATTENTION] IMPORTANT: Prendre snapshot avant!

# VM éteinte:
# VM -> Settings -> Hard Disk
# Disk size: 20 GB -> 30 GB
# [Expand]

# Ou CLI:
vmware-vdiskmanager -x 30GB Ubuntu.vmdk


# ÉTENDRE PARTITION DANS VM:
# ═════════════════════════

# Démarrer VM

# Vérifier nouveau espace:
lsblk
# sda    30G <- Disque agrandi
# └─sda2 20G <- Partition pas encore étendue

# Méthode 1: growpart + resize2fs
# ───────────────────────────────
# Installer cloud-guest-utils:
sudo apt install cloud-guest-utils

# Étendre partition:
sudo growpart /dev/sda 2
# CHANGED: partition=2 start=... old: size=... new: size=...

# Étendre filesystem ext4:
sudo resize2fs /dev/sda2

# Vérifier:
df -h
# /dev/sda2  30G <- Étendu! [OK]

# Méthode 2: parted + resize2fs
# ─────────────────────────────
sudo parted /dev/sda
# (parted) resizepart 2 100%
# (parted) quit

sudo resize2fs /dev/sda2


# LVM (Logical Volume Manager):
# ════════════════════════════

# Si partition utilise LVM:

# Vérifier PV:
sudo pvdisplay
# PV Size: 20 GB <- Avant

# Étendre PV:
sudo pvresize /dev/sda2

# Vérifier:
sudo pvdisplay
# PV Size: 30 GB <- Après [OK]

# Étendre LV:
sudo lvextend -l +100%FREE /dev/ubuntu-vg/ubuntu-lv

# Étendre filesystem:
sudo resize2fs /dev/ubuntu-vg/ubuntu-lv


# RÉDUIRE DISQUE (DANGEREUX!):
# ════════════════════════════

# [ATTENTION] Risque perte données!
# [ATTENTION] Backup complet avant!

# 1. Dans VM, réduire filesystem:
sudo resize2fs /dev/sda2 15G

# 2. Réduire partition (parted):
sudo parted /dev/sda
# (parted) resizepart 2 15GB
# (parted) quit

# 3. Éteindre VM

# 4. Réduire VMDK (CLI host):
vmware-vdiskmanager -k Ubuntu.vmdk  # Defragment
vmware-vdiskmanager -r source.vmdk -t 0 smaller.vmdk  # Créer plus petit


# ═══ 9.4 DISQUES MULTIPLES ET RAID ═══

# SOFTWARE RAID DANS VM:
# ═════════════════════

# Ajouter 3 disques virtuels:
# sdb, sdc, sdd (20GB chacun)

# Installer mdadm:
sudo apt install mdadm

# Créer RAID 5 (3 disques):
sudo mdadm --create /dev/md0 --level=5 --raid-devices=3 /dev/sdb /dev/sdc /dev/sdd

# Formater RAID:
sudo mkfs.ext4 /dev/md0

# Monter:
sudo mkdir /mnt/raid5
sudo mount /dev/md0 /mnt/raid5

# Vérifier status:
cat /proc/mdstat
# md0 : active raid5 sdd[2] sdc[1] sdb[0]
#       41943040 blocks level 5, 64k chunk


# LVM SUR PLUSIEURS DISQUES:
# ═════════════════════════

# Créer Physical Volumes:
sudo pvcreate /dev/sdb /dev/sdc /dev/sdd

# Créer Volume Group:
sudo vgcreate data-vg /dev/sdb /dev/sdc /dev/sdd

# Créer Logical Volume (40GB sur 60GB total):
sudo lvcreate -n data-lv -L 40G data-vg

# Formater:
sudo mkfs.ext4 /dev/data-vg/data-lv

# Monter:
sudo mount /dev/data-vg/data-lv /mnt/data


# ═══ 9.5 SNAPSHOTS DISQUES ═══

# DIFFÉRENCE VM SNAPSHOT vs DISQUE SNAPSHOT:
# ═══════════════════════════════════════════

# VM Snapshot:
# • État complet VM (CPU, RAM, disques)
# • Pris via interface VMware
# • Rapide restauration

# Disque Snapshot (Filesystem):
# • Snapshot filesystem (LVM, ZFS, Btrfs)
# • Pris dans VM (commandes Linux)
# • Indépendant VMware


# LVM SNAPSHOTS:
# ═════════════

# Créer snapshot LV:
sudo lvcreate -s -n data-lv-snap -L 5G data-vg/data-lv
# -s: snapshot
# -L 5G: Taille snapshot (stocke changements)

# Monter snapshot (read-only):
sudo mkdir /mnt/snap
sudo mount -o ro /dev/data-vg/data-lv-snap /mnt/snap

# Restaurer depuis snapshot:
sudo lvconvert --merge /dev/data-vg/data-lv-snap
# Reboot requis pour activation

# Supprimer snapshot:
sudo lvremove /dev/data-vg/data-lv-snap


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 10: PERFORMANCE STOCKAGE
# ═══════════════════════════════════════════════════════════════════


# ═══ 10.1 OPTIMISATION DISQUES ═══

# CHOISIR BON TYPE DISQUE:
# ═══════════════════════

# SCSI (Recommandé):
# • Performance excellente
# • Support hot-add
# • Max 4 contrôleurs × 15 disques = 60 disques

# NVMe (Performance max):
# • Latence ultra-basse
# • Throughput élevé
# • Idéal VMs I/O intensives (bases de données)

# SATA:
# • Performance moyenne
# • Max 4 contrôleurs × 30 disques = 120 disques

# IDE (Legacy):
# • Performance limitée
# • Compatibilité anciennes VMs
# • Max 4 disques


# PARAVIRTUAL SCSI (PVSCSI):
# ═════════════════════════

# Adaptateur SCSI optimisé VMware
# Meilleure performance que SCSI standard

# Activer:
# VM -> Settings -> Hard Disk -> Advanced
# Virtual device node: SCSI (0:0)
# 
# Change Type -> VMware Paravirtual


# THICK vs THIN PROVISIONING:
# ═══════════════════════════

# Production -> Thick Eager Zeroed
# Dev/Test -> Thin Provisioned
# 
# Benchmark (iops):
# Thick Eager: 10,000 IOPS
# Thick Lazy:   9,500 IOPS
# Thin:         7,000 IOPS


# DISQUE HOST (SSD vs HDD):
# ════════════════════════

# SSD/NVMe:
# • Random I/O: 100,000+ IOPS
# • Latence: <1ms
# • Recommandé VMs

# HDD:
# • Random I/O: 100-200 IOPS
# • Latence: 5-10ms
# • OK stockage bulk, archives


# ═══ 10.2 MONITORING PERFORMANCES ═══

# DANS LA VM (LINUX):
# ══════════════════

# iostat (I/O statistics):
sudo apt install sysstat
iostat -x 1
# Device tps    kB_read/s kB_wrtn/s
# sda    150    1500      3000

# iotop (top pour I/O):
sudo apt install iotop
sudo iotop
# Total DISK READ: 10.50 M/s | Total DISK WRITE: 5.23 M/s

# dstat (stats système):
sudo apt install dstat
dstat -cdngy
# ----total-cpu-usage---- -dsk/total- -net/total-
# usr sys idl wai hiq siq| read  writ| recv  send


# VMWARE WORKSTATION:
# ══════════════════

# VM -> Statistics
# Affiche:
# • CPU usage
# • Memory usage
# • Disk I/O
# • Network I/O


# ═══ 10.3 DÉFRAGMENTATION ET COMPACTION ═══

# POURQUOI DÉFRAGMENTER?
# ═════════════════════

# Thin provisioned disks grandissent mais ne rétrécissent pas
# Supprimer 10GB fichiers -> .vmdk reste même taille
# Défragmentation libère espace


# DÉFRAGMENTER DISQUE VM:
# ══════════════════════

# 1. Dans VM, remplir espace libre de zéros:
# Linux:
sudo dd if=/dev/zero of=/zerofile bs=1M
sudo rm /zerofile

# Windows:
# Télécharger SDelete (Sysinternals)
sdelete -z C:

# 2. Éteindre VM

# 3. Défragmenter VMDK (host):
vmware-vdiskmanager -d Ubuntu.vmdk

# 4. Compacter (shrink):
vmware-vdiskmanager -k Ubuntu.vmdk

# Résultat:
# Avant: Ubuntu-flat.vmdk 30GB
# Après: Ubuntu-flat.vmdk 18GB (12GB libérés) [OK]


# ═══ 10.4 SHARED STORAGE (ESXi) ═══

# DATASTORES:
# ══════════

# VMFS (VMware File System):
# • Filesystem cluster-aware
# • Accès concurrent multiple ESXi
# • Support fichiers énormes (VMs TB)

# NFS (Network File System):
# • Partage réseau
# • Flexible, facile setup
# • Performance correcte

# iSCSI (Internet SCSI):
# • SAN over IP
# • Performance excellente
# • Coût modéré


# vSAN (VMware vSAN):
# ══════════════════

# Software-defined storage
# Disques locaux serveurs ESXi -> Pool storage partagé
# Réplication, haute disponibilité intégrée


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 5: STOCKAGE ET DISQUES VIRTUELS
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 5:
# 
# [OK] Types disques virtuels (Thick Lazy/Eager, Thin)
# [OK] Ajouter disque virtuel à VM
# [OK] Partitionner et formater (fdisk, mkfs.ext4)
# [OK] Monter disques (mount, fstab)
# [OK] Redimensionner disques (growpart, resize2fs)
# [OK] RAID software (mdadm, RAID 5)
# [OK] LVM (PV, VG, LV, snapshots)
# [OK] Types contrôleurs (SCSI, NVMe, SATA, IDE, PVSCSI)
# [OK] Optimisation performance (SSD, Thick Eager, PVSCSI)
# [OK] Monitoring I/O (iostat, iotop, dstat)
# [OK] Défragmentation et compaction VMDK
# [OK] Shared storage ESXi (VMFS, NFS, iSCSI, vSAN)
# 
# [OBJECTIF] PROCHAINE PARTIE:
# Partie 6 couvre Fonctionnalités Avancées et Production
# (vMotion, HA, DRS, Backup, Automation, Best Practices)
# 
# --- FIN PARTIE 5 ---

# ═══════════════════════════════════════════════════════════════════
# GUIDE VMWARE ULTRA-DÉTAILLÉ POUR GRANDS DÉBUTANTS
# PARTIE 6: FONCTIONNALITÉS AVANCÉES ET PRODUCTION
# Pour Étudiants et Administrateurs Linux/Réseaux (Ubuntu)
# ═══════════════════════════════════════════════════════════════════


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 11: VMWARE ESXi - HYPERVISEUR BARE-METAL
# ═══════════════════════════════════════════════════════════════════


# ═══ 11.1 INTRODUCTION ESXi ═══

# WORKSTATION vs ESXi:
# ═══════════════════

# VMware Workstation (Type 2):
# ┌────────────────────────┐
# │ Applications           │
# ├────────────────────────┤
# │ Workstation / VMs      │
# ├────────────────────────┤
# │ OS Host (Ubuntu)       │
# ├────────────────────────┤
# │ Hardware               │
# └────────────────────────┘

# VMware ESXi (Type 1):
# ┌────────────────────────┐
# │ VMs                    │
# ├────────────────────────┤
# │ ESXi Hypervisor        │
# ├────────────────────────┤
# │ Hardware               │
# └────────────────────────┘

# Avantages ESXi:
# [OK] Performance maximale (accès direct hardware)
# [OK] Densité VMs élevée (100+ VMs par serveur)
# [OK] Features entreprise (vMotion, HA, DRS)
# [OK] Stabilité production (99.9%+ uptime)

# Cas d'usage:
# • Workstation: Desktop, développement, tests
# • ESXi: Production, datacenter, cloud privé


# VERSIONS ESXi:
# ═════════════

# ESXi Free (Gratuit):
# • Hypervisor complet
# • Pas de vCenter (gestion centralisée)
# • Pas de vMotion (migration live)
# • Pas de HA (haute disponibilité)
# • Max 8 vCPUs par VM
# -> Parfait: Lab, PME, apprentissage

# ESXi Standard:
# • vCenter support
# • vMotion
# • APIs complètes
# -> Petites infrastructures

# ESXi Enterprise Plus:
# • DRS (load balancing auto)
# • HA (redémarrage auto VMs)
# • Distributed Switch
# • NIOC/SIOC (QoS réseau/storage)
# -> Grandes entreprises


# PRÉREQUIS MATÉRIEL ESXi:
# ════════════════════════

# CPU:
# • 64-bit x86 avec VT-x/AMD-V
# • Minimum: 2 cores
# • Recommandé: 8+ cores

# RAM:
# • Minimum: 4GB (ESXi seulement)
# • Recommandé: 32GB+ (pour VMs)

# Disque:
# • Minimum: 8GB pour boot
# • Recommandé: SSD 120GB+ pour VMs

# Réseau:
# • Minimum: 1 NIC Gigabit
# • Recommandé: 2+ NICs (redondance)

# HCL (Hardware Compatibility List):
# Vérifier compatibilité sur:
# www.vmware.com/resources/compatibility/search.php


# ═══ 11.2 INSTALLER ESXi ═══

# TÉLÉCHARGER ESXi:
# ════════════════

# Site: my.vmware.com
# 1. Créer compte VMware
# 2. Downloads -> vSphere
# 3. Télécharger ESXi 8.0 ISO
#    VMware-VMvisor-Installer-8.0U2-xxxxx.x86_64.iso
# 4. Obtenir licence gratuite (Free ESXi)

# CRÉER USB BOOTABLE (Linux):
# ═══════════════════════════

# Insérer clé USB (min 8GB)
# Identifier périphérique:
lsblk
# sdb    8G  (USB)

# [ATTENTION] ATTENTION: Va effacer USB!
sudo dd if=VMware-VMvisor-Installer-8.0U2-xxxxx.iso of=/dev/sdb bs=4M status=progress
sudo sync

# Ou utiliser Rufus (Windows) / Etcher (multi-plateforme)


# INSTALLATION ESXi:
# ═════════════════

# 1. Booter serveur depuis USB

# Écran: Welcome
# ─────────────
# [Enter] Continue

# Écran: EULA
# ──────────
# [F11] Accept and Continue

# Écran: Select disk
# ─────────────────
# Sélectionner disque installation (SSD 120GB)
# [Enter]

# Écran: Keyboard layout
# ─────────────────────
# US Default
# [Enter]

# Écran: Root password
# ───────────────────
# Enter password: ********
# Confirm password: ********
# -> Mot de passe fort (min 8 caractères)
# [Enter]

# Écran: Scan for VMs
# ──────────────────
# (Optionnel, skip)
# [Enter]

# Écran: Confirm install
# ─────────────────────
# [ATTENTION] Will erase all data on disk!
# [F11] Install

# Installation...
# ─────────────
# Durée: 5-10 minutes
# 
# Installation Complete
# [Enter] Reboot


# POST-INSTALLATION:
# ═════════════════

# Retirer USB et reboot

# Écran jaune ESXi:
# ────────────────
# VMware ESXi 8.0.2
# 
# Management Network:
# IPv4 Address: 192.168.1.100 (DHCP)
# 
# [F2] Customize System
# [F12] Shut Down/Restart


# CONFIGURATION RÉSEAU:
# ════════════════════

# Appuyer [F2] -> Login
# Username: root
# Password: ********

# Configure Management Network
# ──────────────────────────
# Network Adapters: vmnic0 (select)
# 
# IPv4 Configuration:
# [WHITE_CIRCLE] DHCP
# [WHITE_CIRCLE] Set static IPv4... [SELECT THIS]
# 
# IPv4 Address: 192.168.1.100
# Subnet mask: 255.255.255.0
# Default gateway: 192.168.1.1
# 
# DNS Configuration:
# Primary DNS: 8.8.8.8
# Hostname: esxi01.lab.local
# 
# [Esc] Exit -> Apply changes and restart? [Y]


# ACCÈS WEB INTERFACE:
# ═══════════════════

# Depuis PC sur même réseau:
# Navigateur: https://192.168.1.100
# 
# Login:
# Username: root
# Password: ********
# 
# Interface web ESXi Host Client s'ouvre [OK]


# ═══ 11.3 GÉRER VMs SUR ESXi ═══

# CRÉER DATASTORE:
# ═══════════════

# Storage -> Datastores -> New datastore
# 
# 1. Type: VMFS
# 2. Name: datastore1
# 3. Device: Select disk (ex: 1TB SSD)
# 4. VMFS version: VMFS6
# 5. Partition: Use full disk
# [Finish]


# UPLOADER ISO:
# ════════════

# Storage -> datastore1 -> Datastore browser
# [Upload]
# Sélectionner ubuntu-22.04.3-live-server-amd64.iso
# Upload...
# 
# ISO dans: [datastore1] /ISO/ubuntu-22.04.3.iso


# CRÉER VM:
# ════════

# Virtual Machines -> Create/Register VM
# 
# 1. Select creation type:
#    [WHITE_CIRCLE] Create a new virtual machine
# 
# 2. Name and guest OS:
#    Name: Ubuntu-Server-01
#    Guest OS family: Linux
#    Guest OS version: Ubuntu Linux (64-bit)
# 
# 3. Storage:
#    Select datastore: datastore1
# 
# 4. Customize settings:
#    CPU: 2
#    Memory: 4096 MB
#    Hard disk 1: 50 GB (Thin provisioned)
#    Network adapter: VM Network
#    CD/DVD: Datastore ISO file
#      -> [datastore1] /ISO/ubuntu-22.04.3.iso
#      [x] Connect at power on
# 
# 5. Ready to complete:
#    [Finish]


# DÉMARRER VM:
# ═══════════

# Virtual Machines -> Ubuntu-Server-01
# [Power on]
# 
# Cliquer console (écran VM):
# Installation Ubuntu démarre...


# VMWARE TOOLS ESXi:
# ═════════════════

# Dans VM Ubuntu (après install OS):
sudo apt update
sudo apt install -y open-vm-tools


# ═══ 11.4 NETWORKING ESXi ═══

# STANDARD VSWITCH:
# ════════════════

# Networking -> Virtual switches -> Add standard virtual switch
# 
# vSwitch name: vSwitch1
# Uplink 1: vmnic1
# MTU: 1500
# [Add]


# PORT GROUPS:
# ═══════════

# Networking -> Port groups -> Add port group
# 
# Name: VLAN-10-Dev
# VLAN ID: 10
# Virtual switch: vSwitch1
# [Add]
# 
# VMs attachées à ce port group seront dans VLAN 10


# MULTI-NIC CONFIGURATION:
# ═══════════════════════

# Exemple 2 NICs:
# vmnic0: Management Network (192.168.1.0/24)
# vmnic1: VM Network (10.0.0.0/24)
# 
# vSwitch0 -> vmnic0 -> Management
# vSwitch1 -> vmnic1 -> VMs


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 12: VCENTER ET FONCTIONNALITÉS ENTREPRISE
# ═══════════════════════════════════════════════════════════════════


# ═══ 12.1 vCENTER SERVER ═══

# POURQUOI vCENTER?
# ════════════════

# Sans vCenter (ESXi standalone):
# • Gérer chaque ESXi séparément
# • Pas de vMotion
# • Pas de HA/DRS
# • Pas de centralization
# 
# Avec vCenter:
# • Gestion centralisée multi-ESXi
# • vMotion (migration live VMs)
# • HA (redémarrage auto VMs)
# • DRS (load balancing auto)
# • Snapshots avancés
# • Backup intégré


# ARCHITECTURE vCENTER:
# ════════════════════

# ┌────────────────────────────────────┐
# │      vCenter Server (VM)           │
# │   (Gestion centralisée)            │
# └──────────┬─────────────────────────┘
#            │
#     ┌──────┴──────┬──────────┬────────┐
#     │             │          │        │
# ┌───[BLACK_DOWN-POINTING_TRIANGLE]────┐  ┌────[BLACK_DOWN-POINTING_TRIANGLE]───┐  ┌───[BLACK_DOWN-POINTING_TRIANGLE]────┐  ...
# │ ESXi-1 │  │ ESXi-2 │  │ ESXi-3 │
# │ 30 VMs │  │ 25 VMs │  │ 28 VMs │
# └────────┘  └────────┘  └────────┘


# INSTALLER vCENTER:
# ═════════════════

# vCenter disponible en 2 versions:
# 1. vCenter Server Appliance (vCSA) -> Recommandé
#    • VM prépackagée (Linux photon)
#    • Déploiement ISO
# 
# 2. vCenter Server for Windows -> Déprécié
#    • Installation sur Windows Server

# Prérequis vCSA:
# • vCPUs: 2-16 (selon taille)
# • RAM: 12-32GB
# • Disque: 415GB+
# • ESXi existant pour héberger vCSA


# ═══ 12.2 vMOTION - MIGRATION À CHAUD ═══

# CONCEPT:
# ═══════

# Migrer VM d'un ESXi à autre SANS ARRÊT
# 
# Avant vMotion:
# ESXi-1: [VM-Ubuntu] (running)
# ESXi-2: (empty)
# 
# Pendant vMotion:
# ESXi-1: [VM-Ubuntu] -> Copying memory...
# ESXi-2: [VM-Ubuntu] <- Receiving...
# 
# Après vMotion:
# ESXi-1: (empty)
# ESXi-2: [VM-Ubuntu] (running) [OK]
# 
# Downtime: <1 seconde (imperceptible)


# PRÉREQUIS vMOTION:
# ═════════════════

# [OK] vCenter Server
# [OK] Shared storage (VMFS/NFS)
# [OK] Compatible CPUs (Intel <-> Intel, AMD <-> AMD)
# [OK] Réseau vMotion dédié (Gigabit+)
# [OK] VMware Tools installé


# CONFIGURER vMOTION:
# ══════════════════

# Sur chaque ESXi:
# 
# 1. Networking -> VMkernel adapters -> Add
# 2. Port group: vMotion-Network
# 3. IPv4: 10.0.10.1 (ESXi-1), 10.0.10.2 (ESXi-2)
# 4. Services: [x] vMotion
# 5. [OK]


# EFFECTUER vMOTION:
# ═════════════════

# Dans vCenter:
# 1. Clic droit VM -> Migrate
# 2. Change host: ESXi-2
# 3. Change datastore: (même datastore shared)
# 4. Network: Keep existing
# 5. vMotion priority: High
# 6. [Finish]
# 
# Migration démarre:
# Task: Relocate virtual machine
# Progress: ████████████ 100%
# Status: Completed [OK]


# QUAND UTILISER vMOTION:
# ══════════════════════

# [OK] Maintenance ESXi (migrer VMs avant)
# [OK] Équilibrage charge (répartir VMs)
# [OK] Upgrade hardware sans downtime
# [OK] Isoler problème hardware


# ═══ 12.3 HA - HAUTE DISPONIBILITÉ ═══

# CONCEPT:
# ═══════

# Redémarrage automatique VMs si ESXi crash
# 
# Scénario:
# ────────
# 1. ESXi-1 héberge 10 VMs
# 2. ESXi-1 crash (hardware failure)
# 3. vCenter détecte failure (15-30 sec)
# 4. VMs redémarrées auto sur ESXi-2, ESXi-3
# 5. Downtime: ~2-5 minutes (reboot VMs)


# ACTIVER HA:
# ══════════

# vCenter:
# 1. Créer Cluster
#    Datacenter -> New Cluster
#    Name: Production-Cluster
#    [x] vSphere HA
#    [x] vSphere DRS
# 
# 2. Ajouter ESXi hosts au cluster
#    Drag ESXi-1, ESXi-2, ESXi-3 -> Cluster
# 
# 3. Configurer HA
#    Cluster -> Configure -> vSphere HA
#    Admission Control:
#      Policy: Host failures cluster tolerates: 1
#      -> Réserve ressources pour 1 host failure


# TESTER HA:
# ═════════

# Simuler failure:
# 1. ESXi-1 -> Shut down (simulate crash)
# 2. Attendre 30 secondes
# 3. VMs ESXi-1 redémarrent sur ESXi-2/3 [OK]


# ═══ 12.4 DRS - DISTRIBUTED RESOURCE SCHEDULER ═══

# CONCEPT:
# ═══════

# Load balancing automatique VMs entre ESXi
# 
# Problème:
# ESXi-1: CPU 90%, RAM 95% (surchargé)
# ESXi-2: CPU 20%, RAM 30% (sous-utilisé)
# 
# Solution DRS:
# DRS migre automatiquement VMs ESXi-1 -> ESXi-2
# Résultat équilibré:
# ESXi-1: CPU 55%, RAM 60%
# ESXi-2: CPU 55%, RAM 60%


# ACTIVER DRS:
# ═══════════

# Cluster -> Configure -> vSphere DRS
# 
# Automation level:
# [WHITE_CIRCLE] Manual (recommandations seulement)
# [WHITE_CIRCLE] Partially automated (confirmer migrations)
# [WHITE_CIRCLE] Fully automated (migrations auto) [PROD]
# 
# Migration threshold:
# Conservative <-─────────────-> Aggressive
# (peu migrations)    (beaucoup migrations)


# RÈGLES DRS:
# ══════════

# VM-VM Affinity:
# ──────────────
# Keep VMs together
# Exemple: Web + DB sur même ESXi (latence)

# VM-VM Anti-Affinity:
# ───────────────────
# Keep VMs apart
# Exemple: 2 VMs critiques sur ESXi différents (HA)

# VM-Host Affinity:
# ────────────────
# VM sur ESXi spécifique
# Exemple: Licence Oracle sur ESXi dédié


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 13: BACKUP ET DISASTER RECOVERY
# ═══════════════════════════════════════════════════════════════════


# ═══ 13.1 STRATÉGIES BACKUP ═══

# 3-2-1 RULE:
# ══════════

# 3: 3 copies données (1 prod + 2 backups)
# 2: 2 médias différents (disque + NAS)
# 1: 1 copie offsite (cloud, autre datacenter)


# MÉTHODES BACKUP VMs:
# ═══════════════════

# 1. Snapshots VMware:
# ───────────────────
# [OK] Rapide (secondes)
# [OK] Point-in-time recovery
# [X] Pas un backup (même storage)
# [X] Impact performance long terme

# 2. Clone VMs:
# ────────────
# [OK] Copie complète
# [X] VM doit être éteinte
# [X] Espace 2× taille VM

# 3. Export OVF/OVA:
# ─────────────────
# [OK] Standard, portable
# [OK] Compression
# [X] Export lent
# [X] VM offline

# 4. Backup software:
# ──────────────────
# [OK] Backup online (VM running)
# [OK] Incrémental (rapide)
# [OK] Planification automatique
# [OK] Rétention policies
# -> RECOMMANDÉ PRODUCTION


# ═══ 13.2 SOLUTIONS BACKUP ═══

# VEEAM BACKUP & REPLICATION:
# ══════════════════════════

# Leader marché backup VMs
# 
# Features:
# • Backup incrémental forever
# • Instant VM recovery (<15 min)
# • Application-aware (SQL, Exchange)
# • Replication VMs
# • Cloud backup

# Exemple workflow:
# ────────────────
# Jour 1: Full backup VM (50GB)
# Jour 2: Incrémental (2GB changements)
# Jour 3: Incrémental (1.5GB)
# ...
# Jour 8: Full backup (50GB)


# VMWARE vSPHERE DATA PROTECTION (VDP):
# ═════════════════════════════════════

# Intégré vSphere
# Basé sur EMC Avamar
# 
# Features:
# • Backup VMs vCenter
# • Déduplication
# • Compression
# • Jusqu'à 8TB


# NAKIVO BACKUP & REPLICATION:
# ═══════════════════════════

# Alternative Veeam
# Plus abordable
# 
# Features:
# • Backup incrémental
# • Site recovery
# • Cross-platform (VMware, Hyper-V)


# BACKUP OPEN-SOURCE:
# ══════════════════

# Bacula:
# • Entreprise-grade
# • Flexible, complexe

# Bareos:
# • Fork Bacula
# • Interface moderne

# UrBackup:
# • Simple, gratuit
# • Client/Server


# ═══ 13.3 BACKUP MANUEL (SCRIPT) ═══

# SCRIPT BACKUP VMs (ESXi):
# ════════════════════════

#!/bin/bash
# backup-vms.sh

# Configuration
DATASTORE="/vmfs/volumes/datastore1"
BACKUP_DIR="/vmfs/volumes/backup-datastore/backups"
DATE=$(date +%Y%m%d-%H%M%S)

# VMs à backup
VMS=("Ubuntu-Server-01" "Web-Server-02")

for VM in "${VMS[@]}"; do
    echo "Backup $VM..."
    
    # Créer snapshot
    vim-cmd vmsvc/snapshot.create $(vim-cmd vmsvc/getallvms | grep "$VM" | awk '{print $1}') "backup-$DATE" "Automated backup" 0 0
    
    # Copier VMDK
    cp -r "$DATASTORE/$VM" "$BACKUP_DIR/$VM-$DATE/"
    
    # Supprimer snapshot
    SNAPSHOT_ID=$(vim-cmd vmsvc/snapshot.get $(vim-cmd vmsvc/getallvms | grep "$VM" | awk '{print $1}') | grep -A1 "Snapshot Name" | tail -1 | awk '{print $2}')
    vim-cmd vmsvc/snapshot.remove $(vim-cmd vmsvc/getallvms | grep "$VM" | awk '{print $1}') $SNAPSHOT_ID
    
    echo "[OK] $VM backup complete"
done

echo "All backups complete!"


# PLANIFIER AVEC CRON:
# ═══════════════════

# ESXi crontab:
# /var/spool/cron/crontabs/root

# Backup quotidien 2h du matin:
0 2 * * * /vmfs/volumes/datastore1/scripts/backup-vms.sh


# ═══ 13.4 DISASTER RECOVERY ═══

# PLAN DR (DISASTER RECOVERY):
# ═══════════════════════════

# 1. RTO (Recovery Time Objective):
#    Temps max acceptable downtime
#    Exemple: 4 heures
# 
# 2. RPO (Recovery Point Objective):
#    Perte données max acceptable
#    Exemple: 1 heure (backup chaque heure)
# 
# 3. Tier applications:
#    • Tier 1 (Critique): RTO 1h, RPO 15min
#    • Tier 2 (Important): RTO 4h, RPO 1h
#    • Tier 3 (Normal): RTO 24h, RPO 24h


# SITE RECOVERY MANAGER (SRM):
# ═══════════════════════════

# Solution VMware DR
# 
# Architecture:
# ┌─────────────────┐       ┌─────────────────┐
# │ Site Principal  │       │ Site DR         │
# │                 │       │                 │
# │ vCenter-1       │[BLACK_LEFT-POINTING_POINTER]─────[BLACK_RIGHT-POINTING_POINTER]│ vCenter-2       │
# │ SRM-1           │       │ SRM-2           │
# │                 │       │                 │
# │ ESXi-1,2,3      │       │ ESXi-4,5,6      │
# │ VMs Production  │ Repli │ VMs Standby     │
# └─────────────────┘       └─────────────────┘

# Failover automatique si site principal down


# TEST DR:
# ═══════

# Tester régulièrement (trimestriel):
# 1. Simuler disaster (shutdown site principal)
# 2. Déclencher failover site DR
# 3. Vérifier VMs démarrent
# 4. Tester applications
# 5. Documenter problèmes
# 6. Failback vers site principal


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 14: AUTOMATION ET SCRIPTING
# ═══════════════════════════════════════════════════════════════════


# ═══ 14.1 PowerCLI (PowerShell VMware) ═══

# INSTALLER PowerCLI:
# ══════════════════

# Windows PowerShell (Admin):
Install-Module -Name VMware.PowerCLI -Scope CurrentUser

# Vérifier:
Get-Module -ListAvailable VMware*


# CONNEXION vCenter:
# ═════════════════

Connect-VIServer -Server vcenter.lab.local -User administrator@vsphere.local -Password P@ssw0rd


# EXEMPLES SCRIPTS PowerCLI:
# ═════════════════════════

# Lister toutes VMs:
Get-VM

# Lister VMs allumées:
Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"}

# Démarrer VM:
Start-VM -VM "Ubuntu-Server-01"

# Arrêter VM:
Stop-VM -VM "Ubuntu-Server-01" -Confirm:$false

# Créer snapshot toutes VMs:
Get-VM | New-Snapshot -Name "Backup-$(Get-Date -Format yyyyMMdd)"

# Rapport ressources VMs:
Get-VM | Select-Object Name, NumCpu, MemoryGB, @{N="DiskGB";E={($_ | Get-HardDisk | Measure-Object -Property CapacityGB -Sum).Sum}} | Export-Csv C:\reports\vm-resources.csv


# SCRIPT AUTOMATION COMPLEXE:
# ═══════════════════════════

# Provisionner 10 VMs identiques:
$template = Get-Template -Name "Ubuntu-Template"
$datastore = Get-Datastore -Name "datastore1"
$cluster = Get-Cluster -Name "Production-Cluster"

1..10 | ForEach-Object {
    $vmName = "WebServer-$_"
    New-VM -Name $vmName -Template $template -Datastore $datastore -ResourcePool $cluster -NetworkName "VLAN-10" -DiskStorageFormat Thin
    Start-VM -VM $vmName
}


# ═══ 14.2 vSphere API (REST) ═══

# AUTHENTIFICATION:
# ════════════════

# Obtenir session token:
curl -X POST https://vcenter.lab.local/rest/com/vmware/cis/session \
  -u 'administrator@vsphere.local:P@ssw0rd' \
  -k

# Response:
# {"value":"abc123def456..."}


# LISTER VMs:
# ══════════

curl -X GET https://vcenter.lab.local/rest/vcenter/vm \
  -H "vmware-api-session-id: abc123def456..." \
  -k


# DÉMARRER VM (Python):
# ════════════════════

import requests
import json

vcenter = "vcenter.lab.local"
username = "administrator@vsphere.local"
password = "P@ssw0rd"

# Login
session = requests.post(
    f"https://{vcenter}/rest/com/vmware/cis/session",
    auth=(username, password),
    verify=False
)
token = session.json()["value"]

# Get VM ID
headers = {"vmware-api-session-id": token}
vms = requests.get(
    f"https://{vcenter}/rest/vcenter/vm",
    headers=headers,
    verify=False
).json()

vm_id = [vm["vm"] for vm in vms["value"] if vm["name"] == "Ubuntu-Server-01"][0]

# Power on
requests.post(
    f"https://{vcenter}/rest/vcenter/vm/{vm_id}/power/start",
    headers=headers,
    verify=False
)


# ═══ 14.3 TERRAFORM VMWARE ═══

# PROVIDER CONFIGURATION:
# ══════════════════════

# main.tf
terraform {
  required_providers {
    vsphere = {
      source = "hashicorp/vsphere"
      version = "2.5.1"
    }
  }
}

provider "vsphere" {
  user           = "administrator@vsphere.local"
  password       = "P@ssw0rd"
  vsphere_server = "vcenter.lab.local"
  allow_unverified_ssl = true
}


# CRÉER VM AVEC TERRAFORM:
# ═══════════════════════

data "vsphere_datacenter" "dc" {
  name = "Datacenter"
}

data "vsphere_datastore" "datastore" {
  name          = "datastore1"
  datacenter_id = data.vsphere_datacenter.dc.id
}

data "vsphere_compute_cluster" "cluster" {
  name          = "Production-Cluster"
  datacenter_id = data.vsphere_datacenter.dc.id
}

data "vsphere_network" "network" {
  name          = "VM Network"
  datacenter_id = data.vsphere_datacenter.dc.id
}

resource "vsphere_virtual_machine" "vm" {
  name             = "terraform-vm-01"
  resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
  datastore_id     = data.vsphere_datastore.datastore.id
  num_cpus         = 2
  memory           = 4096
  guest_id         = "ubuntu64Guest"

  network_interface {
    network_id = data.vsphere_network.network.id
  }

  disk {
    label            = "disk0"
    size             = 50
    thin_provisioned = true
  }
}


# DÉPLOYER:
# ════════

terraform init
terraform plan
terraform apply


# ═══ 14.4 ANSIBLE VMWARE ═══

# INSTALLER MODULE:
# ════════════════

pip install ansible
pip install pyvmomi


# PLAYBOOK ANSIBLE:
# ════════════════

# vmware-deploy.yml
---
- name: Deploy VMs on vSphere
  hosts: localhost
  gather_facts: false
  vars:
    vcenter_hostname: "vcenter.lab.local"
    vcenter_username: "administrator@vsphere.local"
    vcenter_password: "P@ssw0rd"
    datacenter_name: "Datacenter"
    cluster_name: "Production-Cluster"
    datastore_name: "datastore1"

  tasks:
    - name: Create VM from template
      community.vmware.vmware_guest:
        hostname: "{{ vcenter_hostname }}"
        username: "{{ vcenter_username }}"
        password: "{{ vcenter_password }}"
        validate_certs: false
        datacenter: "{{ datacenter_name }}"
        cluster: "{{ cluster_name }}"
        name: "ansible-vm-01"
        template: "Ubuntu-Template"
        datastore: "{{ datastore_name }}"
        state: poweredon
        hardware:
          memory_mb: 4096
          num_cpus: 2
        networks:
          - name: "VM Network"
            ip: 192.168.1.150
            netmask: 255.255.255.0
            gateway: 192.168.1.1
        customization:
          hostname: ansible-vm-01


# EXÉCUTER:
# ════════

ansible-playbook vmware-deploy.yml


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 15: MONITORING ET PERFORMANCE
# ═══════════════════════════════════════════════════════════════════


# ═══ 15.1 MONITORING ESXi ═══

# ESXTOP (CLI):
# ════════════

# SSH sur ESXi:
esxtop

# Écran CPU:
# ────────
# c (CPU mode)
# Affiche: %USED, %RDY (CPU ready time)
# 
# %RDY < 5%: OK
# %RDY > 10%: Problème (overcommitment)

# Écran Memory:
# ────────────
# m (Memory mode)
# Affiche: PMEM (physical), VMKMEM, MCTL (balloon)

# Écran Network:
# ─────────────
# n (Network mode)
# Affiche: pNIC, vNIC, TX/RX paquets

# Écran Disk:
# ──────────
# d (Disk mode)
# Affiche: DAVG (latency), KAVG, GAVG


# PERFORMANCE CHARTS (WEB):
# ════════════════════════

# ESXi Host Client:
# Monitor -> Performance
# 
# Charts disponibles:
# • CPU Usage
# • Memory Usage
# • Disk I/O
# • Network I/O
# 
# Real-time (20 sec interval)


# ═══ 15.2 MONITORING vCENTER ═══

# vCENTER PERFORMANCE:
# ═══════════════════

# vCenter -> Cluster -> Monitor -> Performance
# 
# Advanced charts:
# • CPU fairness (DRS)
# • Memory balloon (contention)
# • Datastore latency
# • Network packet loss


# ALARMS:
# ══════

# Configure -> Alarm Definitions
# 
# Exemples alarms:
# • Host CPU usage > 90% (5 min)
# • VM memory usage > 95%
# • Datastore usage > 85%
# • Host connection lost
# 
# Actions:
# • Send email
# • Run script
# • Send SNMP trap


# ═══ 15.3 SOLUTIONS MONITORING TIERCES ═══

# PROMETHEUS + GRAFANA:
# ════════════════════

# Architecture:
# vCenter -> VMware Exporter -> Prometheus -> Grafana
# 
# VMware Exporter:
# • Collecte métriques vSphere
# • Expose format Prometheus
# 
# Dashboard Grafana:
# • CPU/RAM/Disk par VM
# • Top 10 VMs consommation
# • Prédiction saturation


# NAGIOS/ICINGA:
# ═════════════

# Plugins VMware:
# • check_vmware_api
# • check_esx
# 
# Checks:
# • ESXi uptime
# • VM state (powered on/off)
# • Datastore free space
# • Snapshot age


# VREALIZE OPERATIONS (vROps):
# ═══════════════════════════

# Solution VMware officielle
# 
# Features:
# • Dashboards avancés
# • Capacity planning
# • Anomaly detection
# • Cost analysis
# • Rightsizing recommendations


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 16: SÉCURITÉ ET BEST PRACTICES
# ═══════════════════════════════════════════════════════════════════


# ═══ 16.1 SÉCURITÉ HYPERVISEUR ═══

# ESXi HARDENING:
# ══════════════

# 1. Firewall ESXi:
# ────────────────
# Security & Users -> Firewall
# Désactiver services inutiles:
# [ ] vSphere Web Client
# [ ] VM console (si pas utilisé)

# 2. Lockdown Mode:
# ────────────────
# Security & Users -> Lockdown Mode: Enabled
# -> Empêche accès direct ESXi (seulement via vCenter)

# 3. SSH/Shell:
# ────────────
# Désactiver SSH quand pas nécessaire
# Services -> TSM-SSH -> Stop

# 4. Mot de passe fort:
# ────────────────────
# Security & Users -> Users
# Politique:
# • Min 15 caractères
# • Complexité élevée
# • Rotation 90 jours

# 5. NTP synchronisation:
# ──────────────────────
# System -> Time & Date
# Use Network Time Protocol: [x]
# NTP servers: pool.ntp.org
# -> Logs horodatés correctement


# CERTIFICATS SSL:
# ═══════════════

# Remplacer certificats self-signed:
# 
# 1. Générer CSR (Certificate Signing Request)
# 2. Obtenir certificat CA
# 3. Installer certificat:
#    Security & Users -> Certificates -> Replace

# Ou utiliser Let's Encrypt (automation)


# ═══ 16.2 SÉCURITÉ RÉSEAU ═══

# VLAN SEGMENTATION:
# ═════════════════

# Séparer trafic par VLANs:
# • VLAN 10: Management (ESXi, vCenter)
# • VLAN 20: vMotion
# • VLAN 30: Storage (iSCSI, NFS)
# • VLAN 100-199: VMs Production
# • VLAN 200-299: VMs Dev/Test


# PRIVATE VLANs (PVLAN):
# ═════════════════════

# Isolation VMs même VLAN
# 
# Types:
# • Promiscuous: Communique avec tous
# • Isolated: Pas de communication inter-VMs
# • Community: Communication dans groupe


# DISTRIBUTED FIREWALL (NSX):
# ══════════════════════════

# Firewall micro-segmentation
# Règles au niveau vNIC VM
# 
# Exemple règle:
# Web Tier -> App Tier: Port 8080 (Allow)
# App Tier -> DB Tier: Port 3306 (Allow)
# Internet -> DB Tier: (Deny)


# ═══ 16.3 SÉCURITÉ VMs ═══

# ISOLATION VMs:
# ═════════════

# Paramètres isolation (.vmx):
isolation.tools.copy.disable = "TRUE"
isolation.tools.paste.disable = "TRUE"
isolation.tools.diskShrink.disable = "TRUE"
isolation.tools.diskWiper.disable = "TRUE"

# Empêche:
# • Copy/paste host <-> guest
# • Shrink disques depuis guest
# • Wipe disques


# ANTIVIRUS VMs:
# ═════════════

# Problème: AV dans chaque VM = overhead
# 
# Solution: VMware NSX Antivirus
# • Agent léger dans VM
# • Scan engine centralisé (appliance)
# • Déduplication scan fichiers identiques


# UPDATES RÉGULIERS:
# ═════════════════

# VMs:
# • Patches OS (Ubuntu: apt update/upgrade)
# • Applications updates
# 
# ESXi:
# • Patches ESXi trimestriels
# • Test lab avant prod
# 
# vCenter:
# • Updates vCenter
# • Snapshots avant updates


# ═══ 16.4 BEST PRACTICES PRODUCTION ═══

# RESSOURCES VMs:
# ══════════════

# [OK] Ne pas over-allocate vCPUs
# VM 1 thread -> 1 vCPU (pas 4)
# 
# [OK] Éviter overcommit RAM >100%
# Swapping = performance catastrophique
# 
# [OK] Thick provisioned production
# Thin = dev/test seulement
# 
# [OK] Séparer OS et données (disques séparés)
# /dev/sda: OS (50GB)
# /dev/sdb: Données (500GB)


# SNAPSHOTS:
# ═════════

# [OK] Supprimer après usage (max 72h)
# Snapshots vieux = fragmentation + espace
# 
# [X] NE PAS snapshots BDD production!
# Corruption possible (transactions)
# -> Utiliser backup application-aware


# NAMING CONVENTIONS:
# ══════════════════

# VMs: [Env]-[App]-[Instance]-[OS]
# Exemples:
# • PROD-WEB-01-Ubuntu22
# • DEV-DB-01-MySQL8
# • TEST-APP-02-Win2022

# Datastores: [Type]-[Location]-[Number]
# • SSD-Rack1-01
# • NFS-NAS-02


# DOCUMENTATION:
# ═════════════

# Maintenir à jour:
# • Architecture réseau (VLANs, IPs)
# • Inventaire VMs (nom, OS, ressources, owner)
# • Procédures DR
# • Contacts escalade
# • Mots de passe (vault sécurisé)


# CHANGE MANAGEMENT:
# ═════════════════

# Process changements:
# 1. Demande changement (ticket)
# 2. Impact analysis
# 3. Approbation
# 4. Planification fenêtre maintenance
# 5. Backup avant changement
# 6. Exécution + tests
# 7. Documentation
# 8. Post-mortem si problème


# CAPACITY PLANNING:
# ═════════════════

# Monitoring tendances:
# • CPU/RAM growth rate
# • Storage growth rate
# • Network bandwidth usage
# 
# Projections:
# Si 10% growth/mois
# -> Saturation dans 6-8 mois
# -> Budget hardware Q3


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 17: TROUBLESHOOTING AVANCÉ
# ═══════════════════════════════════════════════════════════════════


# ═══ 17.1 PROBLÈMES COURANTS ET SOLUTIONS ═══

# PROBLÈME: VM lente (performance)
# ═══════════════════════════════

# Diagnostic:
# ──────────
# 1. Vérifier CPU Ready time (esxtop):
esxtop
# c (CPU mode)
# %RDY > 10%? -> Overcommit CPU

# Solutions:
# • Réduire vCPUs VM
# • Migrer VMs vers autre host
# • Upgrade CPU host

# 2. Vérifier Memory ballooning:
esxtop
# m (Memory mode)
# MCTL > 0? -> Contention RAM

# Solutions:
# • Augmenter RAM host
# • Réduire RAM VMs inutilisées
# • Activer compression mémoire

# 3. Vérifier Disk latency:
esxtop
# d (Disk mode)
# DAVG > 20ms? -> Problème I/O

# Solutions:
# • Migrer vers SSD
# • Réduire VMs sur datastore
# • Vérifier RAID/SAN


# PROBLÈME: VM ne démarre pas
# ═══════════════════════════

# Message: "Unable to power on VM"
# 
# Causes fréquentes:
# ─────────────────

# 1. Disque host plein:
df -h /vmfs/volumes/datastore1
# Use%: 99% <- PROBLÈME

# Solution:
# • Supprimer snapshots
# • Supprimer VMs inutilisées
# • Thin provisioning

# 2. Fichier verrouillé (.lck):
ls -la /vmfs/volumes/datastore1/VM/
# .lck directory present

# Solution:
# • Identifier ESXi avec lock
# • Reboot ESXi (si nécessaire)
# • Supprimer .lck (dernier recours)

# 3. VMDK corrompu:
# vmware.log contient: "Failed to open disk"

# Solution:
# • Restaurer depuis backup
# • Réparer VMDK (vmware-vdiskmanager)


# PROBLÈME: Réseau VM ne fonctionne pas
# ═════════════════════════════════════

# 1. Vérifier vNIC connecté:
# VM Settings -> Network Adapter
# [x] Connected
# [x] Connect at power on

# 2. Vérifier port group:
# Networking -> Port groups
# Port group existe? VMs attachées?

# 3. Dans VM, vérifier interface:
ip link show ens33
# state DOWN <- Problème

# Solution:
sudo ip link set ens33 up

# 4. Vérifier DHCP/IP:
ip addr show ens33
# Pas d'IP? -> DHCP fail

# Solution:
sudo dhclient ens33


# PROBLÈME: ESXi ne répond plus (PSOD)
# ════════════════════════════════════

# PSOD = Purple Screen of Death
# 
# Causes:
# • Driver hardware incompatible
# • RAM défectueuse
# • Overheating

# Actions:
# 1. Noter code erreur PSOD
# 2. Vérifier logs: /var/log/vmkernel.log
# 3. Tester RAM (memtest86+)
# 4. Vérifier température CPU
# 5. Update firmware/drivers
# 6. VMware KB: kb.vmware.com


# ═══ 17.2 LOGS ET DIAGNOSTICS ═══

# LOGS ESXi:
# ═════════

# SSH ESXi:
# ────────

# VMkernel log (système):
tail -f /var/log/vmkernel.log

# Hostd log (management):
tail -f /var/log/hostd.log

# VMware log (VMs):
tail -f /var/log/vmware.log

# Auth log (authentification):
tail -f /var/log/auth.log


# LOGS VM:
# ═══════

# VM folder:
cd /vmfs/volumes/datastore1/Ubuntu-Server/

# vmware.log (dernière session):
tail -100 vmware.log

# vmware-1.log, vmware-2.log (précédentes):
ls -lh vmware*.log


# GÉNÉRER BUNDLE SUPPORT:
# ══════════════════════

# ESXi:
# ────
vm-support
# Génère: esx-hostname-YYYY-MM-DD--HH.MM.tgz
# Contient tous logs + config

# vCenter:
# ───────
# Web UI -> Administration -> Support -> Export logs


# ═══════════════════════════════════════════════════════════════════
# CHAPITRE 18: MIGRATION ET UPGRADE
# ═══════════════════════════════════════════════════════════════════


# ═══ 18.1 MIGRER WORKSTATION -> ESXi ═══

# MÉTHODE 1: OVF/OVA EXPORT/IMPORT
# ════════════════════════════════

# Workstation:
# ───────────
# 1. File -> Export to OVF
# 2. Format: OVA (single file)
# 3. Fichier: Ubuntu.ova

# ESXi:
# ────
# 1. File -> Deploy OVF Template
# 2. Upload Ubuntu.ova
# 3. Configure: datastore, network
# 4. [Finish]

# Post-migration:
# ──────────────
# • Vérifier VMware Tools (upgrade si nécessaire)
# • Reconfigurer network (Bridged -> VM Network)
# • Tester application


# MÉTHODE 2: VMware vCenter Converter
# ═══════════════════════════════════

# Outil gratuit VMware
# Convertit:
# • Physical machine -> VM (P2V)
# • VM Workstation -> ESXi
# • VM VirtualBox -> VMware
# 
# Download: vmware.com/products/converter


# ═══ 18.2 UPGRADE ESXi ═══

# UPGRADE PROCESS:
# ═══════════════

# Prérequis:
# ─────────
# [OK] Backup complet VMs
# [OK] vMotion VMs vers autre host (si cluster)
# [OK] Télécharger ISO ESXi nouvelle version
# [OK] Vérifier HCL (compatibilité hardware)

# Méthode 1: ISO Upgrade
# ─────────────────────
# 1. Upload ISO vers datastore
# 2. Host -> Update -> Upload ISO
# 3. Pre-check compatibility
# 4. Install update (reboot)

# Méthode 2: CLI (esxcli)
# ──────────────────────
# Upload VIB (VMware Installation Bundle):
esxcli software vib update -d /vmfs/volumes/datastore1/updates/ESXi800-update.zip

# Reboot:
reboot

# Vérifier version:
vmware -v
# VMware ESXi 8.0.2 build-xxxxxx


# ROLLBACK SI PROBLÈME:
# ════════════════════

# ESXi garde version précédente:
esxcli software vib list | grep -i bootbank

# Rollback:
esxcli system boot set-bootbank -p 1
reboot


# ═══ 18.3 UPGRADE HARDWARE VM ═══

# UPGRADE VM HARDWARE VERSION:
# ═══════════════════════════

# VM hardware version = compatibilité features
# 
# VM hardware 13 (ESXi 6.5)
# v Upgrade
# VM hardware 20 (ESXi 8.0)
# -> Nouvelles features disponibles

# Prérequis:
# ─────────
# [ATTENTION] Backup VM (irréversible!)
# [ATTENTION] VM doit être éteinte

# Upgrade:
# ───────
# VM -> Upgrade VM Compatibility
# Target compatibility: ESXi 8.0 and later
# [OK]

# Vérifier:
# ────────
# VM -> Summary
# VM Version: 20 [OK]


# ═══════════════════════════════════════════════════════════════════
# ANNEXES: RESSOURCES ET RÉFÉRENCES
# ═══════════════════════════════════════════════════════════════════


# ═══ RESSOURCES OFFICIELLES ═══

# Documentation VMware:
# https://docs.vmware.com

# VMware Knowledge Base:
# https://kb.vmware.com

# VMware Communities (Forum):
# https://communities.vmware.com

# VMware Hands-on Labs (HOL):
# https://hol.vmware.com
# -> Labs gratuits online (ESXi, vSphere, NSX)

# VMware Learning Platform:
# https://mylearn.vmware.com


# ═══ CERTIFICATIONS VMWARE ═══

# VCP-DCV (VMware Certified Professional - Data Center Virtualization):
# • Niveau: Intermédiaire
# • Prérequis: Formation officielle VMware
# • Examen: 2V0-21.23 (70 questions, 135 min)
# • Prix: ~250€

# Parcours:
# 1. VCA (Associate) - Débutant
# 2. VCP (Professional) - Intermédiaire <- POPULAIRE
# 3. VCAP (Advanced Professional) - Avancé
# 4. VCDX (Design Expert) - Expert


# ═══ LIVRES RECOMMANDÉS ═══

# "Mastering VMware vSphere 8"
# Auteur: Nick Marshall, Mike Laverick
# 
# "VMware vSphere 8 Cookbook"
# Auteur: Abhilash G B
# 
# "Learning VMware vSphere"
# Auteur: Rebecca Fitzhugh


# ═══ COMMUNAUTÉS ET BLOGS ═══

# VMware vExpert Community:
# https://vexpert.vmware.com

# VMTN (VMware Technology Network):
# https://blogs.vmware.com

# Reddit r/vmware:
# https://reddit.com/r/vmware


# ═══ OUTILS COMPLÉMENTAIRES ═══

# RVTools:
# • Inventaire VMs
# • Rapport ressources
# • Export Excel
# https://www.robware.net/rvtools

# vCheck:
# • Health check automatisé
# • Rapport email quotidien
# • PowerShell script
# https://github.com/alanrenouf/vCheck-vSphere

# Veeam ONE:
# • Monitoring gratuit
# • Alertes
# • Capacity planning


# ═══ LABS ET PRACTICE ═══

# Créer Lab Home (Budget ~1000€):
# ──────────────────────────────

# Serveur:
# • HP ProLiant DL380 Gen9 (occasion ~400€)
# • 2× Xeon E5-2680v4 (28 cores total)
# • 128GB RAM DDR4
# • 2× SSD 500GB (RAID 1)
# • 2× NIC Gigabit

# NAS (Storage):
# • Synology DS220+ (~300€)
# • 2× HDD 4TB
# • NFS/iSCSI

# Switch:
# • Cisco SG300-28 (managed, ~150€)
# • VLAN support

# Configuration:
# • ESXi-1 sur serveur
# • Nested ESXi-2, ESXi-3 (VMs)
# • vCenter (VM)
# • 20-30 VMs lab


# ═══════════════════════════════════════════════════════════════════
# FIN PARTIE 6: FONCTIONNALITÉS AVANCÉES ET PRODUCTION
# ═══════════════════════════════════════════════════════════════════

# [DOCS] RÉCAPITULATIF PARTIE 6:
# 
# [OK] ESXi hypervisor bare-metal (installation, configuration)
# [OK] vCenter Server (gestion centralisée)
# [OK] vMotion (migration live VMs)
# [OK] HA (haute disponibilité automatique)
# [OK] DRS (load balancing automatique)
# [OK] Backup strategies (3-2-1 rule, Veeam, VDP)
# [OK] Disaster Recovery (RTO, RPO, SRM)
# [OK] Automation (PowerCLI, API REST, Terraform, Ansible)
# [OK] Monitoring (esxtop, vCenter, Prometheus, Nagios)
# [OK] Sécurité (hardening, certificates, segmentation)
# [OK] Best practices production (ressources, naming, documentation)
# [OK] Troubleshooting avancé (PSOD, logs, diagnostics)
# [OK] Migration (Workstation->ESXi, P2V)
# [OK] Upgrade (ESXi, VM hardware)
# [OK] Ressources (certifications, labs, communautés)
# 
# [COURS] FÉLICITATIONS!
# 
# Vous avez maintenant une compréhension complète de VMware,
# de l'installation basique de Workstation jusqu'aux fonctionnalités
# entreprise avancées d'ESXi et vSphere.
# 
# PROCHAINES ÉTAPES:
# 1. Pratiquer dans lab home
# 2. Approfondir sujets spécifiques (réseaux, storage, automation)
# 3. Passer certification VCP-DCV
# 4. Contribuer communautés (forums, blogs)
# 5. Expérimenter technologies avancées (NSX, vSAN, Tanzu)
# 
# BONNE CHANCE DANS VOTRE PARCOURS VMWARE! [RAPIDE]
# 
# --- FIN PARTIE 6 ET FIN DU GUIDE COMPLET ---