From 1e2bcf21cffd73d0cec48ed365e13275f5bfdd35 Mon Sep 17 00:00:00 2001 From: Serge NOEL Date: Fri, 20 Nov 2026 15:27:51 +0100 Subject: [PATCH] =?UTF-8?q?Regroupement=20de=20la=20cha=C3=AEne=20de=20tes?= =?UTF-8?q?ts=20de=20charge=20beWeapon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - template/ : build Packer du template Windows 11 (ex /data/Installer/MyTemplate) - deploy/ : OpenTofu + playbooks Ansible (ex /data/Tofu) - bin/Deploy : menu de déploiement (lien depuis /usr/local/bin/Deploy) - jeton API Proxmox sorti des playbooks vers deploy/proxmox-secret.yml (hors git) - README.md : documentation de la structure et du mode opératoire - Ameliorations.md : recommandations pour fiabiliser les mesures - tests/ (dépôt beWeapon-LT) et archives/ exclus Co-Authored-By: Claude Opus 5.5 --- .gitignore | 41 ++ Ameliorations.md | 77 ++++ README.md | 237 +++++++++++ bin/Deploy | 153 +++++++ deploy/.terraform.lock.hcl | 24 ++ deploy/get_ips.yaml | 38 ++ deploy/info.yaml | 77 ++++ deploy/main.tf | 107 +++++ deploy/proxmox-secret.yml.sample | 2 + deploy/start-2.yaml | 89 +++++ deploy/start_and_get_ips.yaml | 97 +++++ deploy/start_and_get_ips_2.yaml | 85 ++++ deploy/start_vms.yaml | 29 ++ deploy/stop.yaml | 38 ++ template/build.sh | 3 + template/generic.pkr.hcl | 119 ++++++ template/http/Autounattend.xml | 226 +++++++++++ template/http/DotNet.ps1 | 10 + template/http/Drivers.ps1 | 12 + template/http/GuestTools.ps1 | 11 + template/http/Passwd.ps1 | 22 ++ template/http/Windows.ps1 | 14 + template/http/beWeapon.ps1 | 46 +++ template/http/s0_autologon.ps1 | 23 ++ template/http/s1_beweapon.ps1 | 58 +++ template/http/s2_appium.ps1 | 98 +++++ template/http/s3_pysnapcap.ps1 | 154 ++++++++ template/http/s4_dotNet.ps1 | 86 ++++ template/http/s5_com0com.ps1 | 132 +++++++ template/http/s6_tasks.ps1 | 242 ++++++++++++ template/http/s7_CDremove.ps1 | 63 +++ template/http/windows-scripts/generalize.ps1 | 71 ++++ template/http/windows-scripts/setup.ps1 | 38 ++ .../windows/Autounattend-win11.xml.pkrtpl | 226 +++++++++++ template/iso/Autounattend.xml | 226 +++++++++++ template/iso/generalize.ps1 | 71 ++++ template/iso/setup.ps1 | 38 ++ template/plugins.pkr.hcl | 9 + template/variables.pkr.hcl | 373 ++++++++++++++++++ template/windows-11.pkrvars.hcl | 33 ++ 40 files changed, 3498 insertions(+) create mode 100644 .gitignore create mode 100644 Ameliorations.md create mode 100644 README.md create mode 100755 bin/Deploy create mode 100644 deploy/.terraform.lock.hcl create mode 100644 deploy/get_ips.yaml create mode 100644 deploy/info.yaml create mode 100644 deploy/main.tf create mode 100644 deploy/proxmox-secret.yml.sample create mode 100644 deploy/start-2.yaml create mode 100644 deploy/start_and_get_ips.yaml create mode 100644 deploy/start_and_get_ips_2.yaml create mode 100644 deploy/start_vms.yaml create mode 100644 deploy/stop.yaml create mode 100755 template/build.sh create mode 100644 template/generic.pkr.hcl create mode 100644 template/http/Autounattend.xml create mode 100644 template/http/DotNet.ps1 create mode 100644 template/http/Drivers.ps1 create mode 100644 template/http/GuestTools.ps1 create mode 100644 template/http/Passwd.ps1 create mode 100644 template/http/Windows.ps1 create mode 100644 template/http/beWeapon.ps1 create mode 100644 template/http/s0_autologon.ps1 create mode 100644 template/http/s1_beweapon.ps1 create mode 100644 template/http/s2_appium.ps1 create mode 100644 template/http/s3_pysnapcap.ps1 create mode 100644 template/http/s4_dotNet.ps1 create mode 100644 template/http/s5_com0com.ps1 create mode 100644 template/http/s6_tasks.ps1 create mode 100644 template/http/s7_CDremove.ps1 create mode 100644 template/http/windows-scripts/generalize.ps1 create mode 100644 template/http/windows-scripts/setup.ps1 create mode 100644 template/http/windows/Autounattend-win11.xml.pkrtpl create mode 100644 template/iso/Autounattend.xml create mode 100644 template/iso/generalize.ps1 create mode 100644 template/iso/setup.ps1 create mode 100644 template/plugins.pkr.hcl create mode 100644 template/variables.pkr.hcl create mode 100644 template/windows-11.pkrvars.hcl diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e11f597 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Scénarios de test : dépôt git indépendant (o.gillet/beWeapon-LT) +/tests/ + +# Résultats, journaux et sauvegardes des campagnes +/archives/ + +# Secrets +*.tfvars +*.tfstate +*.tfstate.* +.terraform/ +my.pkrvars.hcl +/deploy/proxmox-secret.yml + +# Données d'exécution +/deploy/machines_ip.csv +/deploy/Status/ + +# Environnement Python du conteneur de déploiement +/deploy/bin/ +/deploy/lib/ +/deploy/lib64 +/deploy/include/ +/deploy/pyvenv.cfg +__pycache__/ + +# Binaires, ISO et installeurs +/template/tmp/ +/template/iso/install/ +*.iso +*.exe +*.msi +*.zip +*.raw +packer_cache/ +crash.log + +# Copies de sauvegarde +*.bak +*.bak_* +*.bak.* diff --git a/Ameliorations.md b/Ameliorations.md new file mode 100644 index 0000000..faa87c9 --- /dev/null +++ b/Ameliorations.md @@ -0,0 +1,77 @@ +# Améliorations proposées + +Analyse du 20/11/2026 : serveur pmx-002, bastion, chaîne Packer / Tofu / beWeapon-LT. +Objectif : des résultats de test **reproductibles**, qui mesurent l'application et non +le bruit de l'infrastructure. + +Priorités : 🔴 forte (cause probable de l'aléa), 🟠 moyenne, 🟢 confort / hygiène. + +--- + +## 1. Constat de départ + +- Dernière campagne (18/11, 30 postes × 200 utilisateurs) : **2 845 étapes réussies pour + 4 578 échecs (62 % d'échecs)**. Temps moyens : connexion 15,3 s, sortie d'équipement 14,3 s. + Avec autant d'échecs, les temps moyens ne sont pas exploitables. La première chose à + faire est d'analyser les messages d'erreur (`error_msg` dans `detailed_user_metrics.csv`). +- Le journal `hypervisor.log` montre des `ConnectionRefusedError` du gestionnaire + multiprocessing : un `pkill` d'un second lancement a tué une campagne en cours. +- Une campagne de référence par paliers (1, 5, 10, 20, 30 postes × 10 utilisateurs, + `RETURN_TIME=60`) a été lancée le 20/11 à 15h22. Journal : + `archives/campagne_reference_20261120_1522.log`, résultats dans `tests/results/`. + +--- + +## 2. Infrastructure (pmx-002) + +| | Constat | Proposition | +|---|---|---| +| 🔴 | Un seul SSD SATA porte les 30 postes, la base beWeaponDB, SqlServer et la passerelle. Latence moyenne depuis le démarrage : 8,5 ms en lecture (normal pour un SSD : < 0,5 ms) | Disque dédié aux postes (achat proposé : NVMe 3,84 To). Laisser la base sur le disque actuel | +| 🔴 | beWeaponDB (VM 230) : 4 vCPU, 4 Go de RAM, disque SATA émulé, pour 30 clients | 8 vCPU, 16 Go de RAM minimum, disque virtio-scsi avec iothread. Surveiller CPU et attentes SQL pendant les tests | +| 🟠 | 140 vCPU alloués pour 40 cœurs physiques. Le turbo baisse quand la charge augmente | Priorité CPU plus haute (`cpuunits`) pour la base et la passerelle ; ne pas dépasser 1 vCPU par thread physique pendant les mesures | +| 🟠 | Sauvegarde à 21h00 (VM 100, 110, 111 et 1007, qui n'existe plus : échec chaque nuit) | Retirer 1007, ajouter le template 1051 et beWeaponDB, ne pas lancer de campagne pendant la sauvegarde | +| 🟢 | `/var` plein à 94 %, `local` à 89 %, groupe de volumes `Pmx` alloué à 98 % | Nettoyage (journaux, ISO, disques orphelins) | +| 🟢 | Pas de métrologie de l'hôte | Installer `sysstat` (ou node_exporter + exporteur PVE) pour corréler CPU, disque et résultats | + +--- + +## 3. Template et postes (Packer / Tofu) + +| | Constat | Proposition | +|---|---|---| +| 🔴 | Matériel émulé : disque système `sata0`, carte réseau `e1000` (forcée dans `main.tf`), affichage `qxl` | Disque `virtio-scsi-single` + `iothread=1` + `discard=on` + `ssd=1`, carte réseau `virtio`, pilotes virtio déjà présents dans le template (`Drivers.ps1`) | +| 🔴 | Aucun réglage Windows pour les tests : Windows Update, Defender, indexation, SysMain, compilation .NET en arrière-plan restent actifs. Au repos, les 30 postes consomment déjà 5,7 cœurs | Ajouter un script de provisioning `s8_tuning.ps1` : désactiver Windows Update et SysMain, exclusions Defender (dossiers beWeapon, Appium, Python), indexation coupée, `ngen executeQueuedItems`, plan d'alimentation « Performances élevées », écran de veille et verrouillage désactivés | +| 🔴 | Clones **liés** (`full = false`) : la première écriture d'un bloc coûte plus cher, un poste neuf n'a pas les mêmes temps qu'un poste déjà utilisé | Clones complets (`full = true`) une fois le disque dédié en place, ou une phase de chauffe identique avant chaque campagne | +| 🟠 | Tofu ajoute un disque `scsi0` de 64 Go vide à chaque poste (en plus de `sata0`) | Supprimer le bloc `disk` de `main.tf` ou en faire le disque système | +| 🟠 | Type CPU `x86-64-v2-AES` | `host` (un seul nœud, pas de migration) | +| 🟠 | Le build Packer crée le `vmid` 901 (`my.pkrvars.hcl`), mais Tofu clone le 1051 (`terraform.tfvars`) | Un seul identifiant de template, mis à jour automatiquement après le build | +| 🟠 | 30 postes démarrés à 1 ou 2 s d'intervalle, campagne lancée juste après | Attendre que le CPU de chaque poste soit stable (ex. < 5 % pendant 5 min, via `etat_vms.py`) avant de lancer | +| 🟢 | `ostype: win10` pour un Windows 11 | `win11` | + +--- + +## 4. Méthode de test (beWeapon-LT) + +| | Constat | Proposition | +|---|---|---| +| 🔴 | Un seul palier de 30 postes par campagne | Paliers (désormais `PALIERS="1 5 10 20 30"`) : la courbe temps de réponse / nombre de postes montre où ça casse | +| 🔴 | Pas de mesure de la variance de base | Lancer `PALIERS="1 1 1 1 1"` : si un seul poste varie déjà, le problème vient du scénario ou de l'application | +| 🔴 | Les durées incluent la recherche des éléments d'interface par Appium (lente et dépendante du CPU). Environ la moitié des recherches se font par `name` (texte affiché), plus lent et plus fragile que `accessibility id` | Généraliser `AccessibilityId` (AutomationId à ajouter dans beWeapon si besoin), des attentes explicites, et chronométrer seulement l'action métier (apparition de l'écran attendu) | +| 🟠 | Moyennes uniquement dans `global_metrics.csv` | Ajouter médiane, p90, p95 et écart-type par étape et par palier ; séparer les échecs par type | +| 🟠 | Correction empirique `t_login - 1.5` dans le scénario | Mesurer le temps réel ou documenter cette correction | +| 🟠 | Délai aléatoire de 10 à 120 s au démarrage de chaque poste (non reproductible) | Graine aléatoire fixe (`random.seed`) pour rejouer exactement le même profil de charge | +| 🟠 | Base régénérée à chaque campagne avec des utilisateurs aléatoires | Jeu de données figé (sauvegarde/restauration de la base Omnitrack avant chaque campagne) : même état de départ | +| 🟢 | Lancement en avant-plan, la campagne meurt si la session ssh tombe | Toujours `setsid nohup` (exemple dans le README) ; empêcher deux lancements simultanés (fichier verrou) | +| 🟢 | `Process_results.py` n'est plus appelé | Rapport automatique par palier en fin de campagne | + +--- + +## 5. Organisation et sécurité + +| | Constat | Proposition | +|---|---|---| +| 🔴 | Mots de passe en clair dans les scripts : `sa` SQL Server (`run-XP.sh`), compte Windows `installer` (Autounattend, variables Packer, `check_wkst.py`, `etat_vms.py`, `inputs-xp.yaml`), et dans la note de la VM 230 dans Proxmox | Fichier d'environnement unique hors git (`~/.loadtests.env`) chargé par les scripts ; mot de passe `sa` à changer | +| 🟠 | Jeton API `root@pam` utilisé partout (Packer, Tofu, Ansible) | Utilisateur Proxmox dédié avec un rôle limité (VM.*, Datastore.AllocateSpace) sur un pool `load-tests` | +| 🟠 | `beWeapon-LT` est suivi par **deux** dépôts : `o.gillet/beWeapon-LT` et `HEXA-H/stid-beweapon` (qui contient une quinzaine de fichiers modifiés non commités) | Garder un seul dépôt ; retirer `beWeapon/beWeapon-LT` de `stid-beweapon` (le chemin est maintenant un lien) | +| 🟢 | Nombreuses copies `*.bak_*`, `*.v3_*`, `main3.tf.bak`… | Supprimer : git conserve l'historique | +| 🟢 | `/usr/local/bin/Deploy` : fonction `follow_link` inexistante, `docker run -it` incompatible avec un lancement automatisé | Options en ligne de commande (`Deploy deploy 30`, `Deploy start`) pour enchaîner déploiement et campagne dans un script | diff --git a/README.md b/README.md new file mode 100644 index 0000000..2eeaa1b --- /dev/null +++ b/README.md @@ -0,0 +1,237 @@ +# Load-Tests : tests de charge beWeapon sur Proxmox + +Ce dépôt regroupe la chaîne complète utilisée pour les tests de montée en charge du +client lourd **beWeapon** : + +1. construction d'un template Windows 11 (Packer) ; +2. déploiement de N postes de test clonés depuis ce template (OpenTofu + Ansible, script `Deploy`) ; +3. exécution d'une campagne de test pilotée par Appium/WinAppDriver (`hypervisor.sh`) ; +4. collecte des résultats (CSV). + +Les améliorations proposées sont listées dans [Ameliorations.md](Ameliorations.md). + +--- + +## 1. Architecture + +``` + Poste admin + │ ssh installer@192.168.100.253 + ▼ + Stid-GW (VM 111) ─── 192.168.100.253 / 192.168.110.x / 192.168.111.x + │ ssh 192.168.111.252 (clé de installer@stid-gw) + ▼ + stid-bastion (VM 100, 192.168.111.252, compte installer) + │ Packer, OpenTofu/Ansible (conteneur docker stid:1.3), scripts Python de test + │ API Proxmox https://192.168.111.220:8006 + ▼ + pmx-002 (Proxmox, 192.168.100.220 / 192.168.111.220) + ├── beWeapon-0..29 VM 400..429 Windows 11, Appium/WinAppDriver, beWeapon (vmbr2, DHCP 192.168.111.x) + ├── beWeaponDB VM 230 Windows, SQL Server, base Omnitrack (192.168.111.200) + ├── SqlServer VM 103 + ├── Stid-GW VM 111 + └── template VM 1051 Win11-beWeapon-nov2026 (source des clones) +``` + +Les postes de test sont sur `vmbr2` (192.168.111.0/24). Ce réseau n'a pas de lien +physique : il n'est joignable que depuis le bastion, la passerelle et le serveur Proxmox. + +--- + +## 2. Arborescence + +Emplacement réel : `/data/Installer/Load-Tests` sur stid-bastion. + +| Dossier | Contenu | Ancien emplacement (lien symbolique conservé) | +|---|---|---| +| `template/` | Build Packer du template Windows 11 | `/data/Installer/MyTemplate` | +| `deploy/` | OpenTofu (`main.tf`) + playbooks Ansible, liste des postes `machines_ip.csv` | `/data/Tofu` | +| `bin/Deploy` | Menu de déploiement des postes | `/usr/local/bin/Deploy` (lien) | +| `tests/` | Scénarios de test beWeapon-LT (Python/Appium) | `/data/stid-beweapon/beWeapon/beWeapon-LT` | +| `archives/` | Résultats et journaux des campagnes passées (hors git) | — | + +Les anciens chemins restent valables grâce aux liens symboliques : les habitudes, le +script `Deploy` (qui monte `/data/Tofu` dans docker) et les environnements Python +(chemins absolus dans `lt-env` et dans le venv de `deploy/`) continuent de fonctionner. + +### Dépôts git + +| Dossier | Dépôt | Remarque | +|---|---|---| +| `Load-Tests/` | `gitea.easylinux.fr/easylinux/Bastion-Stid` | Ce dépôt : template, deploy, bin, documentation | +| `tests/` | `o.gillet/beWeapon-LT` (alias ssh `gitea-jump`) | Dépôt indépendant, **exclu** de ce dépôt | +| `/data/stid-beweapon` | `gitea.aipice.local/HEXA-H/stid-beweapon` | Ancien dépôt, contient aussi une copie de beWeapon-LT (voir Ameliorations.md) | + +Ne sont **pas** versionnés (voir `.gitignore`) : secrets (`*.tfvars`, `*.tfstate`, +`my.pkrvars.hcl`, `deploy/proxmox-secret.yml`), venv Python, ISO et installeurs +(`template/tmp/`, `template/iso/install/`, `*.iso`), résultats (`archives/`). + +### Dossiers obsolètes (à ne plus utiliser) + +- `/data/Installer/Template` : ancienne version du build Packer. +- `/data/stid-beweapon/beWeapon/LoadTests` : ancienne version des scénarios (remplacée par beWeapon-LT). +- `/data/stid-beweapon.old`, `/usr/local/bin/Deploy.old`, fichiers `*.bak*`. + +--- + +## 3. Étape 1 : construire le template (Packer) + +Dossier : `template/` + +```bash +cd /data/Installer/Load-Tests/template +./build.sh # packer build -var-file=my.pkrvars.hcl -var-file=windows-11.pkrvars.hcl -on-error=ask . +``` + +| Fichier | Rôle | +|---|---| +| `generic.pkr.hcl` | Source `proxmox-iso` + liste des scripts de provisioning | +| `variables.pkr.hcl` | Déclaration des variables et valeurs par défaut | +| `my.pkrvars.hcl` | Connexion Proxmox (jeton API), nœud, `vmid`, stockages (**secret, hors git**) | +| `windows-11.pkrvars.hcl` | ISO Windows 11 25H2, ISO virtio-win, taille disque | +| `iso/` | `Autounattend.xml`, `setup.ps1`, `generalize.ps1` et installeurs → `unattended-win.iso` | +| `http/*.ps1` | Scripts de provisioning exécutés via WinRM | + +Ordre des scripts de provisioning (`generic.pkr.hcl`) : + +| Script | Rôle | +|---|---| +| `Drivers.ps1`, `GuestTools.ps1` | Pilotes virtio et agent QEMU | +| `DotNet.ps1`, `Windows.ps1` | Runtimes .NET 10 (x64) et Windows Desktop (x86) | +| `s0_autologon.ps1` | Ouverture de session automatique du compte `Installer` (indispensable pour l'UI Automation) | +| `s1_beweapon.ps1` | Installation de beWeapon (`setup_weapon_tracer*.msi`, `OmnitrackSettings`) | +| `s2_appium.ps1` | Node.js, Appium, WinAppDriver | +| `s3_pysnapcap.ps1` | Extraction de l'outil pysnapcap | +| `s4_dotNet.ps1` | .NET Framework 3.5 | +| `s6_tasks.ps1` | Copie des scripts de démarrage (`start_beweapon.ps1`…), pilotes système, mode développeur Windows (requis par WinAppDriver) | + +`s5_com0com.ps1` (ports série virtuels) et `s7_CDremove.ps1` existent mais ne sont pas appelés. + +Le template produit porte le `vmid` défini dans `my.pkrvars.hcl` (actuellement **901**), +alors que le déploiement clone le template **1051** (`deploy/terraform.tfvars`). +Après un nouveau build, il faut mettre à jour `vm_template_id`. + +--- + +## 4. Étape 2 : déployer les postes (`Deploy`) + +```bash +Deploy # menu interactif +``` + +| Choix | Action | Commande exécutée dans le conteneur `stid:1.3` (dossier `deploy/` monté sur `/data`) | +|---|---|---| +| 1 | Déploiement de N postes (1 à 30) | `tofu apply -var="vm_count=N" -auto-approve` | +| 2 | Démarrage des postes + récupération des IP | `ansible-playbook start-2.yaml` | +| 3 | Arrêt des postes | `ansible-playbook stop.yaml` | +| 4 | Suppression des postes | `tofu destroy -auto-approve` | +| I | Information (IP des postes) | `ansible-playbook info.yaml` | + +Caractéristiques des postes (`deploy/main.tf`) : VM `beWeapon-`, vmid `400+n`, +**clone lié** du template 1051 sur `PVE-Thin`, 4 vCPU `x86-64-v2-AES`, 6 Go de RAM, +carte réseau e1000 sur `vmbr2`. + +Les IP (DHCP) sont lues par l'agent QEMU et écrites dans **`deploy/machines_ip.csv`** +(`Nom_VM,ID_Proxmox,Adresse_IP`). Ce fichier est l'entrée de la campagne de test. + +Le jeton API Proxmox des playbooks est dans `deploy/proxmox-secret.yml` (hors git, +modèle : `proxmox-secret.yml.sample`). Celui d'OpenTofu est dans `deploy/terraform.tfvars`. + +Séquence habituelle : **1** (déploiement) → **2** (démarrage + IP) → attendre que +Windows ait fini de démarrer → campagne. + +--- + +## 5. Étape 3 : lancer une campagne (`hypervisor.sh`) + +```bash +cd /data/Installer/Load-Tests/tests # obligatoire : les scripts utilisent des chemins relatifs +./hypervisor.sh # 1 palier de 30 postes × 200 utilisateurs (comportement historique) + +# Campagne par paliers (montée en charge) : +PALIERS="1 5 10 20 30" USERS_PER_WKST=10 RETURN_TIME=60 ./hypervisor.sh + +# Campagne longue détachée de la session ssh : +PALIERS="1 5 10 20 30" USERS_PER_WKST=10 RETURN_TIME=60 \ + setsid nohup ./hypervisor.sh > ../archives/campagne_$(date +%Y%m%d_%H%M).log 2>&1 < /dev/null & +``` + +Déroulement de `hypervisor.sh` : + +1. arrête les sessions Python d'un test précédent (`pkill`) ; +2. active le venv `lt-env` ; +3. lit les IP dans `/data/Tofu/machines_ip.csv` ; +4. **vérifie les postes** avec `check_wkst.py` (VM joignable, Appium, beWeapon). Si un poste est KO, le test est annulé ; +5. **archive** le contenu de `results/` dans `../archives/results_` ; +6. pour chaque palier, appelle `run-XP.sh 9995 9985 1 1 `. + +`run-XP.sh ` : + +| Étape | Script | Rôle | +|---|---|---| +| 1 | `Generate-Users.py`, `Generate-Items.py` | Génère `results/NewUsers.sql`, `results/NewItems.sql` | +| 2 | `Import-Users-SQLcmd.py`, `Import-Items-SQLcmd.py` | Import dans la base `Omnitrack` (192.168.111.200) | +| 3 | `Generate-Yaml.py` | Répartit utilisateurs et équipements par poste → `results/inputs-xp.yaml` | +| 4 | `s1_a_RFID_time_beWeapon.py` | Scénario : un processus par poste, pilotage de beWeapon via Appium | + +Les étapes 1 et 2 ne sont exécutées qu'au premier palier (`SKIP_DB=1` ensuite). + +### Variables d'environnement + +| Variable | Défaut | Effet | +|---|---|---| +| `PALIERS` | `30` | Liste des nombres de postes à tester successivement | +| `USERS_PER_WKST` | `200` | Utilisateurs (sessions) enchaînés par poste | +| `RETURN_TIME` | `300` | Secondes entre la sortie et le retour d'un équipement | +| `USER_PAUSE` | `0` | Pause entre deux utilisateurs d'un même poste | +| `CHECK_WKST=0` | | Désactive la vérification préalable des postes | +| `REPAIR_WKST=1` | | Tente de réparer les postes (relance d'Appium, pare-feu) avant la vérification | +| `SKIP_KO=1` | | Lance le test sans les postes KO | +| `SKIP_DB=1` | | Ne régénère pas et ne réimporte pas utilisateurs et équipements | + +### Scénario `s1_a_RFID_time_beWeapon.py` + +Pour chaque poste (en parallèle), après un délai aléatoire de 10 à 120 s, puis pour chaque utilisateur : + +1. connexion à beWeapon (`LOGIN_OUTPUT`) ; +2. changement de site (`CHANGE_LOCATION`) ; +3. sortie de l'équipement par RFID (`EQUIPMENT_OUTPUT`) ; +4. déconnexion (`LOGOUT_OUTPUT`) ; +5. attente de `RETURN_TIME` secondes, puis connexion, retour de l'équipement et déconnexion (`*_INPUT`). + +Un temps de réflexion de 2 s sépare les actions. + +--- + +## 6. Résultats + +Dossier `tests/results/` (campagne en cours), puis `archives/results_/` : + +| Fichier | Contenu | +|---|---| +| `detailed_user_metrics.csv` | Une ligne par étape : date, site, poste, utilisateur, étape, PASS/FAIL, durée (s), erreur | +| `global_metrics.csv` | Une ligne par palier : nb postes, utilisateurs/poste, succès, échecs, temps moyens par type d'étape | +| `logs.csv` | Journal détaillé de tous les processus | +| `inputs-xp.yaml` | Jeu de données du test (contient des mots de passe) | +| `NewUsers.sql`, `NewItems.sql`, `sites.json` | Données injectées dans la base | + +Outils annexes dans `tests/` : + +| Script | Rôle | +|---|---| +| `check_wkst.py [--check-only]` | Vérifie (et répare) Appium, beWeapon et le pare-feu de chaque poste via WinRM | +| `etat_vms.py` | Relevé de l'état des postes (CSV dans `etat_vms/`) | +| `beweapon_metrics.py --since "AAAA-MM-JJ HH:MM"` | Récupère les métriques collectées sur les postes | +| `Process_results.py` | Mise en forme des résultats (non appelé par défaut) | + +--- + +## 7. Dépannage + +| Symptôme | Piste | +|---|---| +| `Test ANNULÉ : n poste(s) KO` | `REPAIR_WKST=1 ./hypervisor.sh` ou `python check_wkst.py` | +| Pas d'IP pour un poste | Agent QEMU non démarré : relancer **2** dans `Deploy`, vérifier la VM dans Proxmox | +| Échecs Appium en série | Session Windows verrouillée ou fermée (connexion RDP sur le poste) : redémarrer le poste | +| `ConnectionRefusedError` dans le journal | Le gestionnaire multiprocessing a été tué (`pkill` d'un autre lancement en parallèle) : ne lancer qu'une campagne à la fois | +| Accès au bastion | Uniquement par rebond : `ssh installer@192.168.100.253` puis `ssh 192.168.111.252` | diff --git a/bin/Deploy b/bin/Deploy new file mode 100755 index 0000000..2fa00d7 --- /dev/null +++ b/bin/Deploy @@ -0,0 +1,153 @@ +#!/bin/bash + +set -e + +SCRIPT_PATH=$(realpath "$(dirname "$(follow_link "$0")")") + +if [ -n "$1" ]; then + CONFIG_PATH=$(realpath "$1") +else + CONFIG_PATH=$(realpath "${SCRIPT_PATH}/config") +fi + +menu_message="Choisir l'action à réaliser" + +# Menu registry +# Format: key="Label|RelativeInputPath" +declare -A MENU_ITEMS=( + [1]="Déploiement postes|deploy" + [2]="Démarrage postes|start" + [3]="Arret des postes|stop" + [4]="Suppression postes|remove" + [I]="Information|info" + [Q]="Quitter|quit" +) + + +dispatch_selection() { + entry="${MENU_ITEMS[$selection]}" + if [[ -z "$entry" ]]; then + echo "Sélection invalide !" + return + fi + + # echo "Entry: $entry" + action=$(echo $entry|cut -f 2 -d '|') + # echo "Action: $action" + + + case "$action" in + "deploy") + echo "" + echo "" + echo "Deployement" + echo "===========" + echo -n "Nombre de machines à déployer : " + read count + if [[ "$count" =~ ^[0-9]+$ ]]; then + # 2. Vérifie si le nombre est dans la plage [1, 30] + if (( count >= 1 && count <= 30 )); then + docker container run -it --rm -v /data/Tofu:/data stid:1.3 tofu apply -var="vm_count=$count" -auto-approve + break + else + echo "Erreur : le nombre doit être compris entre 1 et 30." + fi + else + echo "Erreur : '$count' n'est pas un nombre valide." + fi + ;; + "start") + echo "Démarrage" + docker container run -it --rm -v /data/Tofu:/data stid:1.3 ansible-playbook start-2.yaml + ;; + "stop") + echo "Arret des VMs" + docker container run -it --rm -v /data/Tofu:/data stid:1.3 ansible-playbook stop.yaml + ;; + "remove") + echo "" + echo "" + echo "Suppression" + docker container run -it --rm -v /data/Tofu:/data stid:1.3 tofu destroy -auto-approve + ;; + "info") + echo "" + echo "" + echo "Information" + echo "===========" + docker container run -it --rm -v /data/Tofu:/data stid:1.3 ansible-playbook info.yaml + echo "Le csv est diponible ici : /data/Tofu/machines_ip.csv" + echo "Contenu : " + cat /data/Tofu/machines_ip.csv + ;; + "quit") + exit 0 + ;; + *) + echo "Option invalide" + ;; + esac + # IFS='|' read -r label path_or_function extra_args <<< "$entry" + + # echo "Vous avez choisi : $IFS" + + + # Decide if it’s a build or a function + #if [[ -d "$SCRIPT_PATH/builds/$path_or_function" ]]; then + # build_template "$label" "$path_or_function" "$extra_args" + #else + # $path_or_function + #fi +} + +press_enter() { + cd "$SCRIPT_PATH" + echo -n "Appuyer sur pour continuer." + read -r + clear +} + +info() { + echo "License: BSD-2" + echo "" + echo "For more information, review the project README." + read -r +} + +quit_program() { + echo "Sortie..." + exit 0 +} + +read_selection() { + read -rp "Selection: " input + echo "${input^^}" # always uppercase +} + +display_menu() { + clear + echo "" + echo " ____ " + echo " / __ \ _____ ____ _ __ ____ ___ ____ _ __ " + echo ' / /_/ // ___// __ \ | |/_// __ `__ \ / __ \ | |/_/ ' + echo " / ____// / / /_/ /_> < / / / / / // /_/ /_> < " + echo '/_/ /_/ \____//_/|_|/_/ /_/ /_/ \____//_/|_| ' + echo "" + echo -n " Choisir une option" + echo "" + echo "" + + for key in $(printf "%s\n" "${!MENU_ITEMS[@]}" | sort -n 2>/dev/null); do + IFS='|' read -r label _ <<< "${MENU_ITEMS[$key]}" + printf " %2s - %s\n" "$key" "$label" + done + echo "" + selection=$(read_selection) +} + +while true; do + display_menu + dispatch_selection + echo "" + read -rp "Appuyer sur pour continuer..." +done diff --git a/deploy/.terraform.lock.hcl b/deploy/.terraform.lock.hcl new file mode 100644 index 0000000..b37e215 --- /dev/null +++ b/deploy/.terraform.lock.hcl @@ -0,0 +1,24 @@ +# This file is maintained automatically by "tofu init". +# Manual edits may be lost in future updates. + +provider "registry.opentofu.org/bpg/proxmox" { + version = "0.107.0" + constraints = ">= 0.50.0" + hashes = [ + "h1:W/DuNEQCgP510F1LfeRCvJa4vXGNT2byH7DzbknpEO4=", + "zh:3c1e298f4f0d954e83d11aaf2400ec242b835ca294f8a94d67bb5ce0b30da0e9", + "zh:4776f7f262728f8e2252360f7d1a4adc853d87d86a7515f4780375c2932ef763", + "zh:53633a48f7fad5561a30b349e7b46c6a7a10a54c99225a4d30a7a24086921098", + "zh:62686df322f773b40c1881eb7932058cbf68101bfa5cd66bc08c9bcb6ad0bdfd", + "zh:62afd9992f9089311a876c7e79d35a8b7935c0c553f6de8fb6ac2b76f5c4a3ce", + "zh:6b379f3858ba8bd548b7d50c07f7fb7eb339d2020c07c2b69aaba1f2247aedae", + "zh:8a520d7df039cb060182683d823d1705423cd9e97936b8e65a27dbf54ea9643a", + "zh:b489993495332d3d4aedfd53a7ff80ce880a58ec575bf3340646791c1803862c", + "zh:db164bc934aaeb56ae1b368208c7cd33f5af5ac84dc98fa7da736a62a5ede143", + "zh:eeb9611c160baf65e6acede202b9d923d185395af2725425c2f8226403675155", + "zh:f24b8014a513483cef883caf58884a380fb51567e50ea5425a3d5ec6629f4a9b", + "zh:f26e0763dbe6a6b2195c94b44696f2110f7f55433dc142839be16b9697fa5597", + "zh:f329a8f344ec11c64686a0b29cd706f5dfedb19925a58aa61fb39f0d0a854619", + "zh:ff0a8a1ac74eaef2826054982d82cb42f1376dac98f3d30f995d60f4964ee7b1", + ] +} diff --git a/deploy/get_ips.yaml b/deploy/get_ips.yaml new file mode 100644 index 0000000..244a621 --- /dev/null +++ b/deploy/get_ips.yaml @@ -0,0 +1,38 @@ +--- +- name: Récupération des IPs des VMs OpenTofu + hosts: localhost + connection: local + gather_facts: false + + tasks: + - name: Récupérer les outputs OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + + - name: Parser le JSON OpenTofu + set_fact: + vms_data: "{{ tofu_output_raw.stdout | from_json }}" + + - name: Préparer la liste des données pour le CSV + set_fact: + vm_list: >- + {%- set result = [] -%} + {%- for name, details in vms_data.items() -%} + {%- set ip = (details.ipv4_addresses | default([[]]))[1] | default(details.ipv4_addresses[0][0] | default('Non attribuée')) -%} + {%- set _ = result.append({'name': name, 'id': details.id, 'ip': ip}) -%} + {%- endfor -%} + {{ result }} + + - name: Afficher les IPs à l'écran + debug: + msg: "VM: {{ item.name }} (ID: {{ item.id }}) -> IP: {{ item.ip }}" + loop: "{{ vm_list }}" + + - name: Générer le fichier CSV machines_ip.csv + copy: + content: | + Nom_VM,ID_Proxmox,Adresse_IP + {% for vm in vm_list %} + {{ vm.name }},{{ vm.id }},{{ vm.ip }} + {% endfor %} + dest: "./machines_ip.csv" diff --git a/deploy/info.yaml b/deploy/info.yaml new file mode 100644 index 0000000..8e1da81 --- /dev/null +++ b/deploy/info.yaml @@ -0,0 +1,77 @@ +--- +- name: Orchestration Démarrage et IPs des VMs + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + ansible_python_interpreter: "/data/bin/python3" + proxmox_api_host: "192.168.111.220" # Votre IP Proxmox + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + csv_file_path: "./machines_ip.csv" + + tasks: + - name: 1. Récupérer les données OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + changed_when: false + + - name: Extraire la liste des VMs + set_fact: + vms_dict: "{{ tofu_output_raw.stdout | from_json }}" + + - name: 3. Interroger l'agent QEMU via l'API Proxmox pour récupérer l'IP + uri: + url: "https://{{ proxmox_api_host }}:8006/api2/json/nodes/{{ item.value.node }}/qemu/{{ item.value.id }}/agent/network-get-interfaces" + method: GET + headers: + Authorization: "PVEAPIToken={{ proxmox_user }}!{{ proxmox_token_id }}={{ proxmox_token_secret }}" + validate_certs: false + status_code: [200] + register: agent_net_info + until: + - agent_net_info.json is defined + - agent_net_info.json.data.result is defined + - (agent_net_info.json.data.result | map(attribute='ip-addresses', default=[]) | flatten | selectattr('ip-address-type', 'equalto', 'ipv4') | map(attribute='ip-address') | reject('equalto', '127.0.0.1') | list | length) > 0 + retries: 30 + delay: 5 + loop: "{{ vms_dict | dict2items }}" + + - name: 4. Extraire et associer les IPs + set_fact: + final_vm_list: >- + {%- set result = [] -%} + {%- for res in agent_net_info.results -%} + {%- set vm_id = res.item.value.id -%} + {%- set vm_name = res.item.value.name -%} + {%- set ifaces = res.json.data.result | default([]) -%} + {%- set ips = [] -%} + {%- for iface in ifaces -%} + {%- set addrs = iface['ip-addresses'] | default([]) -%} + {%- for addr in addrs -%} + {%- if addr['ip-address-type'] == 'ipv4' and addr['ip-address'] != '127.0.0.1' -%} + {%- set _ = ips.append(addr['ip-address']) -%} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {%- set main_ip = ips[0] | default('Non attribuee') -%} + {%- set _ = result.append({'name': vm_name, 'id': vm_id, 'ip': main_ip}) -%} + {%- endfor -%} + {{ result }} + + - name: 5. Afficher les résultats à l'écran + debug: + msg: "VM {{ item.name }} (ID: {{ item.id }}) -> IP: {{ item.ip }}" + loop: "{{ final_vm_list }}" + + - name: 6. Générer le fichier CSV + copy: + content: | + Nom_VM,ID_Proxmox,Adresse_IP + {% for vm in final_vm_list %} + {{ vm.name }},{{ vm.id }},{{ vm.ip }} + {% endfor %} + dest: "{{ csv_file_path }}" diff --git a/deploy/main.tf b/deploy/main.tf new file mode 100644 index 0000000..ef8d666 --- /dev/null +++ b/deploy/main.tf @@ -0,0 +1,107 @@ +# Déploiement de VM Windows sur Proxmox avec Terraform + +terraform { + required_providers { + proxmox = { + source = "bpg/proxmox" + version = ">= 0.50.0" + } + } +} + +provider "proxmox" { + endpoint = var.proxmox_endpoint + api_token = var.proxmox_token + insecure = true +} + +variable "proxmox_token" { + description = "Token d'accès" + type = string + sensitive = true +} + +variable "proxmox_endpoint" { + description = "URL de l'API Proxmox (ex: https://192.168.100.220:8006/api2/json)" + type = string +} + +#variable "proxmox_username" { +# description = "Utilisateur Proxmox (ex: root@pam)" +# type = string +#} + +#variable "proxmox_password" { +# description = "Mot de passe Proxmox" +# type = string +# sensitive = true +#} + +variable "vm_count" { + description = "Nombre de VM à déployer" + type = number +} + +variable "vm_template" { + description = "Nom du template Windows à cloner" + type = string +} + +variable "vm_template_id" { + description = "ID du template Windows à cloner" + type = number +} + +resource "proxmox_virtual_environment_vm" "test" { + count = var.vm_count + name = "beWeapon-${count.index}" + node_name = "pmx-002" # À adapter selon votre cluster + vm_id = 400 + count.index + started = false + clone { + vm_id = var.vm_template_id + full = false + } + cpu { + cores = 4 + type = "x86-64-v2-AES" + } + memory { + dedicated = 6144 + } + operating_system { + type = "win10" + } + network_device { + bridge = "vmbr2" + model = "e1000" + } + disk { + datastore_id = "PVE-Thin" + size = 64 + interface = "scsi0" + } + agent { + enabled = true + } + + timeout_clone = 1800 + # timeouts { + # create = "60m" + # update = "60m" + # delete = "30m" + # } + +} + +output "vms_info" { + value = { + for idx, vm in proxmox_virtual_environment_vm.test : vm.name => { + id = vm.id + name = vm.name + node = vm.node_name + ipv4_addresses = vm.ipv4_addresses + } + } + description = "Informations sur les VMs déployées" +} diff --git a/deploy/proxmox-secret.yml.sample b/deploy/proxmox-secret.yml.sample new file mode 100644 index 0000000..2f15505 --- /dev/null +++ b/deploy/proxmox-secret.yml.sample @@ -0,0 +1,2 @@ +# Copier en proxmox-secret.yml et renseigner le secret du jeton API Proxmox root@pam!Stid +proxmox_token_secret: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" diff --git a/deploy/start-2.yaml b/deploy/start-2.yaml new file mode 100644 index 0000000..1b29742 --- /dev/null +++ b/deploy/start-2.yaml @@ -0,0 +1,89 @@ +--- +- name: Orchestration Démarrage et IPs des VMs + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + ansible_python_interpreter: "/data/bin/python3" + proxmox_api_host: "192.168.111.220" # Votre IP Proxmox + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + csv_file_path: "./machines_ip.csv" + + tasks: + - name: 1. Récupérer les données OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + changed_when: false + + - name: Extraire la liste des VMs + set_fact: + vms_dict: "{{ tofu_output_raw.stdout | from_json }}" + + - name: 2. Démarrer toutes les VMs sur Proxmox + community.proxmox.proxmox_kvm: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + node: "{{ item.value.node }}" + state: started + loop: "{{ vms_dict | dict2items }}" + + - name: 3. Interroger l'agent QEMU via l'API Proxmox pour récupérer l'IP + uri: + url: "https://{{ proxmox_api_host }}:8006/api2/json/nodes/{{ item.value.node }}/qemu/{{ item.value.id }}/agent/network-get-interfaces" + method: GET + headers: + Authorization: "PVEAPIToken={{ proxmox_user }}!{{ proxmox_token_id }}={{ proxmox_token_secret }}" + validate_certs: false + status_code: [200] + register: agent_net_info + until: + - agent_net_info.json is defined + - agent_net_info.json.data.result is defined + - (agent_net_info.json.data.result | map(attribute='ip-addresses', default=[]) | flatten | selectattr('ip-address-type', 'equalto', 'ipv4') | map(attribute='ip-address') | reject('equalto', '127.0.0.1') | list | length) > 0 + retries: 30 + delay: 5 + loop: "{{ vms_dict | dict2items }}" + + - name: 4. Extraire et associer les IPs + set_fact: + final_vm_list: >- + {%- set result = [] -%} + {%- for res in agent_net_info.results -%} + {%- set vm_id = res.item.value.id -%} + {%- set vm_name = res.item.value.name -%} + {%- set ifaces = res.json.data.result | default([]) -%} + {%- set ips = [] -%} + {%- for iface in ifaces -%} + {%- set addrs = iface['ip-addresses'] | default([]) -%} + {%- for addr in addrs -%} + {%- if addr['ip-address-type'] == 'ipv4' and addr['ip-address'] != '127.0.0.1' -%} + {%- set _ = ips.append(addr['ip-address']) -%} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {%- set main_ip = ips[0] | default('Non attribuee') -%} + {%- set _ = result.append({'name': vm_name, 'id': vm_id, 'ip': main_ip}) -%} + {%- endfor -%} + {{ result }} + + - name: 5. Afficher les résultats à l'écran + debug: + msg: "VM {{ item.name }} (ID: {{ item.id }}) -> IP: {{ item.ip }}" + loop: "{{ final_vm_list }}" + + - name: 6. Générer le fichier CSV + copy: + content: | + Nom_VM,ID_Proxmox,Adresse_IP + {% for vm in final_vm_list %} + {{ vm.name }},{{ vm.id }},{{ vm.ip }} + {% endfor %} + dest: "{{ csv_file_path }}" diff --git a/deploy/start_and_get_ips.yaml b/deploy/start_and_get_ips.yaml new file mode 100644 index 0000000..a526232 --- /dev/null +++ b/deploy/start_and_get_ips.yaml @@ -0,0 +1,97 @@ +--- +- name: Orchestration Démarrage et IPs des VMs + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + proxmox_api_host: "192.168.111.220" + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + csv_file_path: "./machines_ip.csv" + ansible_python_interpreter: "/data/bin/python3" + + tasks: + - name: 1. Récupérer les données OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + changed_when: false + + - name: Extraire la liste des VMs + set_fact: + vms_dict: "{{ tofu_output_raw.stdout | from_json }}" + + - name: 2. Démarrer toutes les VMs sur Proxmox en parallèle + community.proxmox.proxmox_kvm: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + node: "{{ item.value.node }}" + state: started + loop: "{{ vms_dict | dict2items }}" + async: 90 + poll: 0 + register: start_jobs + + - name: Attendre le déclenchement complet des démarrages + async_status: + jid: "{{ item.ansible_job_id }}" + loop: "{{ start_jobs.results }}" + when: item.ansible_job_id is defined + until: async_result.finished + retries: 30 + delay: 2 + register: async_result + + - name: 3. Récupérer les informations réseau via l'Agent QEMU + community.proxmox.proxmox_vm_info: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + register: vm_details + loop: "{{ vms_dict | dict2items }}" + + - name: 4. Construire la liste finale avec les adresses IPv4 + set_fact: + final_vm_list: >- + {%- set result = [] -%} + {%- for res in vm_details.results -%} + {%- set vm_id = res.item.value.id -%} + {%- set vm_name = res.item.value.name -%} + {%- set ifaces = res.proxmox_vms[0].network_interfaces | default([]) -%} + {%- set ips = [] -%} + {%- for iface in ifaces if iface.name != 'lo' -%} + {%- for ip in iface.ip_addresses | default([]) -%} + {%- if ip.address is defined and (ip.address.startswith('192.') or ip.address.startswith('10.')) -%} + {%- set _ = ips.append(ip.address) -%} + {%- elif ip is string and (ip.startswith('192.') or ip.startswith('10.')) -%} + {%- set _ = ips.append(ip) -%} + {%- endif -%} + {%- for_end -%} + {%- endfor -%} + {%- set main_ip = ips[0] | default('Non attribuee') -%} + {%- set _ = result.append({'name': vm_name, 'id': vm_id, 'ip': main_ip}) -%} + {%- endfor -%} + {{ result }} + + - name: 5. Afficher les résultats à l'écran + debug: + msg: "VM {{ item.name }} (ID: {{ item.id }}) -> IP DHCP: {{ item.ip }}" + loop: "{{ final_vm_list }}" + + - name: 6. Écrire le fichier CSV + copy: + content: | + Nom_VM,ID_Proxmox,Adresse_IP + {% for vm in final_vm_list %} + {{ vm.name }},{{ vm.id }},{{ vm.ip }} + {% endfor %} + dest: "{{ csv_file_path }}" diff --git a/deploy/start_and_get_ips_2.yaml b/deploy/start_and_get_ips_2.yaml new file mode 100644 index 0000000..fde2afb --- /dev/null +++ b/deploy/start_and_get_ips_2.yaml @@ -0,0 +1,85 @@ +--- +- name: Orchestration Démarrage et IPs des VMs + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + proxmox_api_host: "192.168.111.220" # Votre nouvelle IP Proxmox + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + csv_file_path: "./machines_ip.csv" + ansible_python_interpreter: "/data/bin/python3" + + tasks: + - name: 1. Récupérer les données OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + changed_when: false + + - name: Extraire la liste des VMs + set_fact: + vms_dict: "{{ tofu_output_raw.stdout | from_json }}" + + - name: 2. Démarrer toutes les VMs sur Proxmox + community.proxmox.proxmox_kvm: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + node: "{{ item.value.node }}" + state: started + loop: "{{ vms_dict | dict2items }}" + + - name: 3. Attendre le boot et l'attribution de l'IP DHCP (Agent QEMU) + community.proxmox.proxmox_vm_info: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + register: vm_details + until: + - vm_details.proxmox_vms[0].network_interfaces is defined + - (vm_details.proxmox_vms[0].network_interfaces | selectattr('name', 'ne', 'lo') | map(attribute='ip_addresses') | flatten | select('match', '^192\\.') | list | length) > 0 + retries: 30 + delay: 5 + loop: "{{ vms_dict | dict2items }}" + + - name: 4. Construire la liste finale avec les adresses IP + set_fact: + final_vm_list: >- + {%- set result = [] -%} + {%- for res in vm_details.results -%} + {%- set vm_id = res.item.value.id -%} + {%- set vm_name = res.item.value.name -%} + {%- set ifaces = res.proxmox_vms[0].network_interfaces | default([]) -%} + {%- set ips = [] -%} + {%- for iface in ifaces if iface.name != 'lo' -%} + {%- for ip in iface.ip_addresses if ip.startswith('192.') or ip.startswith('10.') -%} + {%- set _ = ips.append(ip) -%} + {%- endfor -%} + {%- endfor -%} + {%- set main_ip = ips[0] | default('Non attribuée') -%} + {%- set _ = result.append({'name': vm_name, 'id': vm_id, 'ip': main_ip}) -%} + {%- endfor -%} + {{ result }} + + - name: 5. Afficher les résultats à l'écran + debug: + msg: "VM {{ item.name }} (ID: {{ item.id }}) -> IP DHCP: {{ item.ip }}" + loop: "{{ final_vm_list }}" + + - name: 6. Écrire dans le fichier CSV + copy: + content: | + Nom_VM,ID_Proxmox,Adresse_IP + {% for vm in final_vm_list %} + {{ vm.name }},{{ vm.id }},{{ vm.ip }} + {% endfor %} + dest: "{{ csv_file_path }}" diff --git a/deploy/start_vms.yaml b/deploy/start_vms.yaml new file mode 100644 index 0000000..68dca6e --- /dev/null +++ b/deploy/start_vms.yaml @@ -0,0 +1,29 @@ +--- +- name: Démarrer les VMs créées par OpenTofu + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + proxmox_api_host: "192.168.111.220" # Votre nouvelle IP Proxmox + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + + tasks: + - name: Récupérer les IDs des VMs via OpenTofu + command: tofu output -json vms_info + register: tofu_output_raw + + - name: Démarrer chaque VM sur Proxmox + community.general.proxmox_kvm: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + node: "{{ item.value.node }}" + state: started + loop: "{{ (tofu_output_raw.stdout | from_json) | dict2items }}" diff --git a/deploy/stop.yaml b/deploy/stop.yaml new file mode 100644 index 0000000..8188425 --- /dev/null +++ b/deploy/stop.yaml @@ -0,0 +1,38 @@ +- name: Orchestration Démarrage et IPs des VMs + hosts: localhost + connection: local + gather_facts: false + vars_files: + - proxmox-secret.yml # secret hors git (voir proxmox-secret.yml.sample) + + vars: + ansible_python_interpreter: "/data/bin/python3" + proxmox_api_host: "192.168.111.220" # Votre IP Proxmox + proxmox_user: "root@pam" + proxmox_token_id: "Stid" + csv_file_path: "./machines_ip.csv" + + tasks: + - name: "1. Récupérer les données OpenTofu" + command: tofu output -json vms_info + register: tofu_output_raw + changed_when: false + + - name: "2. Extraire la liste des VMs" + set_fact: + vms_dict: "{{ tofu_output_raw.stdout | from_json }}" + + - name: "3. Arreter les postes de travail sur Proxmox" + community.proxmox.proxmox_kvm: + api_host: "{{ proxmox_api_host }}" + api_user: "{{ proxmox_user }}" + api_token_id: "{{ proxmox_token_id }}" + api_token_secret: "{{ proxmox_token_secret }}" + validate_certs: false + vmid: "{{ item.value.id }}" + node: "{{ item.value.node }}" + state: stopped + loop: "{{ vms_dict | dict2items }}" + # async: 300 + # poll: 0 + diff --git a/template/build.sh b/template/build.sh new file mode 100755 index 0000000..69a66ce --- /dev/null +++ b/template/build.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +packer build -var-file=my.pkrvars.hcl -var-file=windows-11.pkrvars.hcl -on-error=ask . diff --git a/template/generic.pkr.hcl b/template/generic.pkr.hcl new file mode 100644 index 0000000..dea5f6c --- /dev/null +++ b/template/generic.pkr.hcl @@ -0,0 +1,119 @@ +locals { +} + +source "proxmox-iso" "vm" { + proxmox_url = "https://${var.proxmox_host}/api2/json" + username = var.proxmox_user + password = var.proxmox_password + token = var.proxmox_token + insecure_skip_tls_verify = var.proxmox_insecure_tls + + vm_id = var.vmid + vm_name = var.name + # template_name = var.name + # template_description = var.description == "" ? "${var.name}, Generated by packer at ${formatdate("YYYY-MM-DD hh:mm:ss", timestamp())}
**User**: Installer" : var.description + node = var.node + pool = var.pool + + cpu_type = var.cpu_type + sockets = var.cpu_sockets + cores = var.cpu_cores + memory = var.memory + + http_interface = var.packer_http_interface + http_bind_address = var.packer_http_bind_address + http_port_min = var.packer_http_port == -1 ? 8000 : "${var.packer_http_port}" + http_port_max = var.packer_http_port == -1 ? 9000 : "${var.packer_http_port}" + + disks { + storage_pool = var.disk_storage_pool + disk_size = var.disk_size + #format = var.disk_format + type = var.disk_type + cache_mode = var.disk_cache + } + + network_adapters { + bridge = var.network_adapter + model = var.network_adapter_model + mac_address = var.network_adapter_mac + vlan_tag = var.network_adapter_vlan == -1 ? "" : "${var.network_adapter_vlan}" + firewall = var.network_adapter_firewall + } + + vga { + type = var.vga_type + memory = var.vga_memory + } + + os = var.os + scsi_controller = var.scsi_controller + onboot = var.start_at_boot + qemu_agent = var.qemu_agent + bios = var.bios + + boot_iso { + iso_file = "${var.iso_storage_pool}:iso/${var.iso_file}" + iso_download_pve = var.iso_download_pve + unmount = var.iso_unmount + } + + # Drivers virtio + additional_iso_files { + #index = 2 + iso_storage_pool = "local" + iso_file = "local:iso/virtio-win.iso" + unmount = false + } + + # --- INJECTION DE L'AUTOUNATTEND VIA ISO --- + additional_iso_files { + # index = 1 + iso_storage_pool = "local" + iso_file = "local:iso/unattended-win.iso" + unmount = false + } + + cloud_init = var.cloud_init + cloud_init_storage_pool = var.cloud_init_storage_pool + + boot = "order=${var.disk_type}0;ide2;net0" + #boot_command = [""] + + boot_wait = var.boot_wait + task_timeout = var.task_timeout + http_directory = var.http_directory + communicator = var.communicator + ssh_username = var.ssh_username + ssh_password = var.ssh_password + ssh_timeout = var.ssh_timeout + winrm_username = var.winrm_username + winrm_password = var.winrm_password + winrm_insecure = var.winrm_insecure + winrm_use_ssl = var.winrm_use_ssl +} + +build { + name = "build" + sources = ["source.proxmox-iso.vm"] + + provisioner "powershell" { + scripts = [ + "http/Drivers.ps1", + "http/GuestTools.ps1", + "http/DotNet.ps1", + "http/Windows.ps1", + "http/s0_autologon.ps1", + "http/s1_beweapon.ps1", + "http/s2_appium.ps1", + "http/s3_pysnapcap.ps1", + "http/s4_dotNet.ps1", + "http/s6_tasks.ps1" + ] + } + + provisioner "windows-restart" { + restart_timeout = "2m" + } + +} diff --git a/template/http/Autounattend.xml b/template/http/Autounattend.xml new file mode 100644 index 0000000..2ee1323 --- /dev/null +++ b/template/http/Autounattend.xml @@ -0,0 +1,226 @@ + + + + + + + + + D:\viostor\w11\amd64 + + + + D:\NetKVM\w11\amd64 + + + + D:\Balloon\w11\amd64 + + + + D:\pvpanic\w11\amd64 + + + + D:\qemupciserial\w11\amd64 + + + + D:\qxldod\w11\amd64 + + + + D:\vioinput\w11\amd64 + + + + D:\viorng\w11\amd64 + + + + D:\vioscsi\w11\amd64 + + + + D:\vioserial\w11\amd64 + + + + + + fr-FR + + fr-FR + fr-FR + fr-FR + fr-FR + + + + + + 1 + BypassTPMCheck + cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassTPMCheck" /t REG_DWORD /d 1 + + + 2 + BypassSecureBootCheck + cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassSecureBootCheck" /t REG_DWORD /d 1 + + + 3 + BypassRAMCheck + cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassRAMCheck" /t REG_DWORD /d 1 + + + + + + + 1 + Primary + 100 + + + 2 + Primary + true + + + + + 1 + 1 + + NTFS + true + + + false + NTFS + C + 2 + 2 + + + + 0 + true + + + OnError + + + true + Installer + Administrators + + Never + + + + + + 0 + 2 + + OnError + false + + + /IMAGE/INDEX + 1 + + + + + + + + + * + UTC + + + false + + + + + true + Remote Desktop + all + + + + + 0 + + + + + + true + Installer + + Stid_2026-03 + true</PlainText> + </Password> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <!-- Enable WinRM service --> + <CommandLine>powershell -ExecutionPolicy Bypass -File E:\setup.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <!-- Configure Remote execution for ansible --> + <Order>2</Order> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible-documentation/refs/heads/devel/examples/scripts/ConfigureRemotingForAnsible.ps1'))"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>3</Order> + <!-- Install Proxmox guest-agent --> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "D:\guest-agent\qemu-ga-x86_64.msi /quiet"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>4</Order> + <!-- Generalize --> + <CommandLine>powershell -ExecutionPolicy Bypass -File E:\generalize.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + </FirstLogonCommands> + <OOBE> + <ProtectYourPC>3</ProtectYourPC> + <HideEULAPage>true</HideEULAPage> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <SkipUserOOBE>true</SkipUserOOBE> + <SkipMachineOOBE>true</SkipMachineOOBE> + </OOBE> + <UserAccounts> + <LocalAccounts> + <LocalAccount wcm:action="add"> + <Name>Installer</Name> + <Group>Administrators</Group> + <Password> + <Value>Stid_2026-03</Value> + <PlainText>true</PlainText> + </Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + </component> + </settings> + <settings pass="offlineServicing"> + <component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <EnableLUA>false</EnableLUA> + </component> + </settings> +</unattend> diff --git a/template/http/DotNet.ps1 b/template/http/DotNet.ps1 new file mode 100644 index 0000000..ec074ff --- /dev/null +++ b/template/http/DotNet.ps1 @@ -0,0 +1,10 @@ +# Journalisation +"Installation du dotnet runtime" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + +# 1. Installation du dotnet runtime (avec attente de la fin du processus) +$installer = Get-ChildItem -Path "D:\install", "E:\install", "F:\install" -Filter "dotnet-runtime-10.0.11-win-x64.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if($installer) { + Start-Process -FilePath $installer.FullName "/passive /norestart" -Wait +} + diff --git a/template/http/Drivers.ps1 b/template/http/Drivers.ps1 new file mode 100644 index 0000000..ba6361d --- /dev/null +++ b/template/http/Drivers.ps1 @@ -0,0 +1,12 @@ +# Journalisation +"Installation des drivers" | Out-File -FilePath "C:\install.log" -Encoding utf8 +# Get-ChildItem -Path "D:\" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + + +# 1. Installation du MSI VirtIO (avec attente de la fin du processus) +$installer = Get-ChildItem -Path "D:\", "E:\", "F:\" -Filter "virtio-win-gt-x64.msi" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if($installer) { + Start-Process -FilePath "msiexec.exe" -ArgumentList "/i $installer.FullName /passive /norestart" -Wait +} + diff --git a/template/http/GuestTools.ps1 b/template/http/GuestTools.ps1 new file mode 100644 index 0000000..08abd8d --- /dev/null +++ b/template/http/GuestTools.ps1 @@ -0,0 +1,11 @@ +# 2. Installation des Guest Tools +"Installation de Guest tools" | Out-File -FilePath "C:\install.log" -Encoding utf8 + +$installer = Get-ChildItem -Path "D:\", "E:\", "F:\" -Filter "virtio-win-guest-tools.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($installer) { + Start-Process -FilePath $installer.FullName -ArgumentList "/passive /norestart" -Wait +} else { + Write-Error "Lecteur CD VirtIO introuvable." + "Lecteur CD VirtIO introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} diff --git a/template/http/Passwd.ps1 b/template/http/Passwd.ps1 new file mode 100644 index 0000000..0fe4add --- /dev/null +++ b/template/http/Passwd.ps1 @@ -0,0 +1,22 @@ +# Journalisation +"Installation des runtimes" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + +# 1. Installation du dotnet runtime (avec attente de la fin du processus) +$installer = Get-ChildItem -Path "D:\install", "E:\install", "F:\install" -Filter "dotnet-runtime-10.0.11-win-x64.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if($installer) { + Start-Process -FilePath $installer.FullName "/passive /norestart" -Wait +} + +# 2. Installation des Guest Tools +$installer = Get-ChildItem -Path "D:\install", "E:\install", "F:\install" -Filter "windowsdesktop-runtime-10.0.12-win-x86.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($installer) { + Start-Process -FilePath $installer.FullName -ArgumentList "/passive /norestart" -Wait +} else { + Write-Error "Lecteur CD VirtIO introuvable." + "Lecteur CD VirtIO introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# $Password = ConvertTo-SecureString "Stid_2026-03" -AsPlainText -Force +# Set-LocalUser -Name "NomUtilisateur" -Password $Password diff --git a/template/http/Windows.ps1 b/template/http/Windows.ps1 new file mode 100644 index 0000000..4c03303 --- /dev/null +++ b/template/http/Windows.ps1 @@ -0,0 +1,14 @@ +# Journalisation +"Installation de windowsdesktop runtime" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + +$installer = Get-ChildItem -Path "D:\install", "E:\install", "F:\install" -Filter "windowsdesktop-runtime-10.0.12-win-x86.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($installer) { + Start-Process -FilePath $installer.FullName -ArgumentList "/passive /norestart" -Wait +} else { + Write-Error "Lecteur CD VirtIO introuvable." + "Lecteur CD VirtIO introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# $Password = ConvertTo-SecureString "Stid_2026-03" -AsPlainText -Force +# Set-LocalUser -Name "NomUtilisateur" -Password $Password diff --git a/template/http/beWeapon.ps1 b/template/http/beWeapon.ps1 new file mode 100644 index 0000000..61b6701 --- /dev/null +++ b/template/http/beWeapon.ps1 @@ -0,0 +1,46 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +# Log initial +"Lancement de beWeapon.ps1..." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + +# Détection robuste du lecteur contenant le dossier "install" +$cdDrive = Get-PSDrive -PSProvider FileSystem | Where-Object { + Test-Path (Path.Combine($_.Root, "install")) +} | Select-Object -First 1 + +if (-not $cdDrive) { + Write-Error "Dossier 'install' introuvable sur les lecteurs de disque." + "Dossier install introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + exit 1 +} + +# Formate proprement le chemin (ex: "E:\install") +$installDir = Join-Path -Path "$($cdDrive.Name):\" -ChildPath "install" +"Dossier d'installation trouvé dans : $installDir" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + +# 1. Installation de beWeapon +$installer = Get-ChildItem -Path $installDir -Filter "*Weapon Tracer*" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($installer) { + Start-Process -FilePath $installer.FullName -ArgumentList "/passive /norestart" -Wait + "beWeapon installé avec succès depuis $($installer.FullName)." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} else { + Write-Error "Installeur beWeapon introuvable dans $installDir" + "beWeapon introuvable dans $installDir." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + exit 1 +} + +# 2. Décompression de OmnitrackSettings.zip +$zipFile = Get-ChildItem -Path $installDir -Filter "OmnitrackSettings.zip" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($zipFile) { + $destinationPath = "C:\ProgramData\Beweis\Omnitrack\" + if (-not (Test-Path -Path $destinationPath)) { + New-Item -Path $destinationPath -ItemType Directory -Force | Out-Null + } + Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force + "Archive OmnitrackSettings.zip extraite dans $destinationPath" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} else { + Write-Warning "Archive OmnitrackSettings.zip introuvable dans $installDir" + "Archive OmnitrackSettings.zip introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} diff --git a/template/http/s0_autologon.ps1 b/template/http/s0_autologon.ps1 new file mode 100644 index 0000000..dfa7b17 --- /dev/null +++ b/template/http/s0_autologon.ps1 @@ -0,0 +1,23 @@ + # ========================================================================= +# Configuration des identifiants (Autologon) +# ========================================================================= +$Username = "Installer" +$Password = "Stid_2026-03" +$Domain = "." + +$RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" + +try { + Write-Host "Configuration de l'Autologon..." -ForegroundColor Cyan + + Set-ItemProperty -Path $RegPath -Name "AutoAdminLogon" -Value "1" -Type String -Force + Set-ItemProperty -Path $RegPath -Name "DefaultUserName" -Value $Username -Type String -Force + Set-ItemProperty -Path $RegPath -Name "DefaultDomainName" -Value $Domain -Type String -Force + Set-ItemProperty -Path $RegPath -Name "DefaultPassword" -Value $Password -Type String -Force + + Write-Host "Autologon configure avec succes pour l'utilisateur '$Username'." -ForegroundColor Green + Write-Host "Au prochain redemarrage, la session s'ouvrira automatiquement." -ForegroundColor Yellow +} +catch { + Write-Error "Echec de la configuration de l'Autologon : $_" +} diff --git a/template/http/s1_beweapon.ps1 b/template/http/s1_beweapon.ps1 new file mode 100644 index 0000000..727e870 --- /dev/null +++ b/template/http/s1_beweapon.ps1 @@ -0,0 +1,58 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +function Write-Log { + param ([string]$Message) + "$Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# Log initial +Write-Log "=== Configuration et installation des prerequis beWeapon ===" +Write-Log "Lancement de de beWeapon.ps1..." + +# Détection automatique du lecteur CD contenant le dossier "install" +$cdDrive = Get-PSDrive -PSProvider FileSystem | Where-Object { + Test-Path (Join-Path $_.Root "install") +} | Select-Object -First 1 + +if (-not $cdDrive) { + Write-Error "Dossier 'install' introuvable sur les lecteurs de disque." + "Dossier install introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + exit 1 +} + +# Définition propre du chemin vers le dossier install +$installDir = Join-Path "$($cdDrive.Name):\" "install" +Write-Log "Dossier d'installation trouve : $installDir" + +# 1. Installation de beWeapon +$installer = Get-ChildItem -Path $installDir -Filter "*weapon_tracer_latest*" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($installer) { + Write-Log "Installeur beWeapon trouve ($($installer.FullName)). Lancement de l'installation silencieuse (/S)..." + Start-Process -FilePath $installer.FullName -ArgumentList "/passive /norestart" -Wait + "beWeapon installe avec succès depuis $($installer.FullName)." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} else { + Write-Error "Installeur beWeapon introuvable dans $installDir" + "beWeapon introuvable dans $installDir." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 + Write-Log "ERREUR lors de l'exécution de l'installeur : $_" + exit 1 +} + +# 2. Décompression de OmnitrackSettings.zip +$zipFile = Get-ChildItem -Path $installDir -Filter "OmnitrackSettings.zip" -ErrorAction SilentlyContinue | Select-Object -First 1 + +if ($zipFile) { + Write-Log "Fichiers de configuration trouves." + $destinationPath = "C:\ProgramData\Beweis\Omnitrack\" + if (-not (Test-Path -Path $destinationPath)) { + New-Item -Path $destinationPath -ItemType Directory -Force | Out-Null + } + Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force + "Archive OmnitrackSettings.zip extraite dans $destinationPath" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} else { + Write-Warning "Archive OmnitrackSettings.zip introuvable dans $installDir" + Write-Log "Fichiers de configuration introuvables." + "Archive OmnitrackSettings.zip introuvable." | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +Write-Log "Fin du script de d'installation de BeWeapon." diff --git a/template/http/s2_appium.ps1 b/template/http/s2_appium.ps1 new file mode 100644 index 0000000..1c966b3 --- /dev/null +++ b/template/http/s2_appium.ps1 @@ -0,0 +1,98 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +function Test-CommandExists { + param ($Command) + return [bool](Get-Command $Command -ErrorAction SilentlyContinue) +} + +function Write-Log { + param ([string]$Message) + "$Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# Logs initiaux +Write-Log "=== Configuration et installation des prerequis Appium ===" +Write-Host "=== Configuration et installation des prerequis Appium ===" -ForegroundColor Cyan + +# 1. Desactivation de l'alias Microsoft Store pour Python (Session courante) +$aliasPath = "$env:LOCALAPPDATA\Microsoft\WindowsApps\python.exe" +if (Test-Path $aliasPath) { + Remove-Item $aliasPath -Force -ErrorAction SilentlyContinue + Write-Log "Alias Microsoft Store pour Python supprime dans $aliasPath" +} + +# 2. Installation de Node.js via winget +if (-not (Test-CommandExists "node")) { + Write-Host "Installation de Node.js..." -ForegroundColor Yellow + Write-Log "Node.js non detecte. Lancement de l'installation via winget..." + + winget install --id OpenJS.NodeJS -e --source winget --accept-source-agreements --accept-package-agreements + + if ($LASTEXITCODE -eq 0) { + Write-Log "Installation de Node.js reussie via winget." + } else { + Write-Log "Erreur lors de l'installation de Node.js (Code sortie : $LASTEXITCODE)." + } +} else { + $nodeVersion = node -v 2>$null + Write-Host "Node.js est deja installe : $nodeVersion" -ForegroundColor Green + Write-Log "Node.js deja installe ($nodeVersion)." +} + +# 3. Installation de Python via winget +if (-not (Test-CommandExists "python")) { + Write-Host "Installation de Python 3.12..." -ForegroundColor Yellow + Write-Log "Python non detecte. Lancement de l'installation de Python 3.12 via winget..." + + winget install --id Python.Python.3.12 -e --source winget --accept-source-agreements --accept-package-agreements + + if ($LASTEXITCODE -eq 0) { + Write-Log "Installation de Python 3.12 reussie via winget." + } else { + Write-Log "Erreur lors de l'installation de Python 3.12 (Code sortie : $LASTEXITCODE)." + } +} else { + $pythonVersion = python --version 2>$null + Write-Host "Python est deja installe : $pythonVersion" -ForegroundColor Green + Write-Log "Python deja installe ($pythonVersion)." +} + +# 4. Rafraîchissement dynamique du PATH dans la session +$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +Write-Log "Variables d'environnement PATH rafraîchies pour la session." + +# 5. Installation d'Appium via NPM +if (Test-CommandExists "npm") { + Write-Host "Installation / Mise a jour d'Appium via npm..." -ForegroundColor Yellow + Write-Log "Lancement de l'installation d'Appium via npm..." + + npm install -g --allow-scripts=appium appium + + if ($LASTEXITCODE -eq 0) { + Write-Host "Appium configure avec succes." -ForegroundColor Green + Write-Log "Appium installe/mis a jour avec succes via npm." + } else { + Write-Log "Erreur lors de l'installation d'Appium via npm (Code sortie : $LASTEXITCODE)." + } +} else { + Write-Error "NPM introuvable. Redemarrez le terminal." + Write-Log "ERREUR : NPM introuvable. Impossible d'installer Appium." + exit 1 +} + +# Recuperation des versions finales pour le rapport +$finalNode = if (Test-CommandExists 'node') { node -v 2>$null } else { "Non disponible" } +$finalPython = if (Test-CommandExists 'python') { python --version 2>$null } else { "Non disponible" } +$finalAppium = if (Test-CommandExists 'appium') { appium -v 2>$null } else { "Non disponible" } + +Write-Host "`n=== Resume des verifications ===" -ForegroundColor Cyan +Write-Host "Node.js : $finalNode" +Write-Host "Python : $finalPython" +Write-Host "Appium : $finalAppium" + +# Journalisation du resume +Write-Log "=== Resume des installations ===" +Write-Log "Node.js : $finalNode" +Write-Log "Python : $finalPython" +Write-Log "Appium : $finalAppium" +Write-Log "Fin du script." diff --git a/template/http/s3_pysnapcap.ps1 b/template/http/s3_pysnapcap.ps1 new file mode 100644 index 0000000..dbc5a51 --- /dev/null +++ b/template/http/s3_pysnapcap.ps1 @@ -0,0 +1,154 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +function Write-Log { + param ([string]$Message) + "$Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# Logs initiaux +Write-Log "=== Configuration et installation des prerequis pysnapcap ===" +Write-Host "=== Configuration et installation des prerequis pysnapcap ===" -ForegroundColor Cyan + +# Detection automatique du lecteur CD contenant le dossier "install" +$cdDrive = Get-PSDrive -PSProvider FileSystem | Where-Object { + Test-Path (Join-Path $_.Root "install") +} | Select-Object -First 1 + +if (-not $cdDrive) { + Write-Error "Dossier 'install' introuvable sur les lecteurs de disque." + Write-Log "ERREUR : Dossier 'install' introuvable sur les lecteurs de disque." + exit 1 +} + +# Definition propre du chemin vers le dossier install +$installDir = Join-Path "$($cdDrive.Name):\" "install" +Write-Log "Dossier d'installation trouve : $installDir" + +# Decompression de pysnapcap.zip +$zipFile = Get-ChildItem -Path $installDir -Filter "pysnapcap.zip" -ErrorAction SilentlyContinue | Select-Object -First 1 +$projectDir = "C:\Users\Installer\Documents\pysnapcap" + +if ($zipFile) { + $destinationPath = "C:\Users\Installer\Documents\" + Write-Log "Archive pysnapcap.zip trouvee ($($zipFile.FullName)). Extraction en cours vers $destinationPath..." + + if (-not (Test-Path -Path $destinationPath)) { + New-Item -Path $destinationPath -ItemType Directory -Force | Out-Null + Write-Log "Dossier de destination $destinationPath cree." + } + + try { + Expand-Archive -Path $zipFile.FullName -DestinationPath $destinationPath -Force -ErrorAction Stop + Write-Log "Archive pysnapcap.zip extraite avec succes dans $destinationPath" + } catch { + Write-Error "Echec de l'extraction de pysnapcap.zip : $_" + Write-Log "ERREUR lors de la decompression de pysnapcap.zip : $_" + exit 1 + } +} else { + Write-Warning "Archive pysnapcap.zip introuvable dans $installDir" + Write-Log "AVERTISSEMENT : Archive pysnapcap.zip introuvable dans $installDir" +} + +# ========================================== +# Detection de l'executable Python +# ========================================== +Write-Log "=== Recherche de Python ===" + +$pythonCmd = Get-Command "py" -ErrorAction SilentlyContinue +if ($pythonCmd) { + $pythonExe = "py" +} else { + $pythonCmd = Get-Command "python" -ErrorAction SilentlyContinue + if ($pythonCmd) { + $pythonExe = "python" + } else { + $possiblePaths = @( + "$env:LocalAppData\Programs\Python\Python*\python.exe", + "C:\Python*\python.exe", + "C:\Program Files\Python*\python.exe" + ) + $foundExe = Get-Item $possiblePaths -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($foundExe) { + $pythonExe = "$($foundExe.FullName)" + } else { + Write-Error "Python introuvable sur la machine." + Write-Log "ERREUR : Python introuvable sur la machine." + exit 1 + } + } +} +Write-Log "Executable Python utilise : $pythonExe" + +# ========================================== +# Installation de Poetry +# ========================================== +Write-Log "=== Installation de Poetry ===" + +try { + (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | & $pythonExe - + Write-Log "Script d'installation de Poetry execute avec succes." +} catch { + Write-Error "Echec de l'installation de Poetry : $_" + Write-Log "ERREUR lors de l'installation de Poetry : $_" + exit 1 +} + +# Ajout du dossier binaire de Poetry au PATH +$possiblePoetryPaths = @( + "$env:APPDATA\Python\Scripts", + "$env:USERPROFILE\.local\bin" +) + +$poetryPath = $possiblePoetryPaths | Where-Object { Test-Path $_ } | Select-Object -First 1 + +if ($poetryPath) { + if ($env:Path -notlike "*$poetryPath*") { + $env:Path += ";$poetryPath" + Write-Log "Chemin $poetryPath ajoute a la session courante." + } + + $userPath = [Environment]::GetEnvironmentVariable("Path", "User") + if ($userPath -notlike "*$poetryPath*") { + [Environment]::SetEnvironmentVariable("Path", "$userPath;$poetryPath", "User") + Write-Log "Chemin $poetryPath ajoute de facon permanente aux variables utilisateur." + } +} else { + Write-Warning "Le dossier d'installation de Poetry est introuvable." + Write-Log "AVERTISSEMENT : Aucun dossier d'installation Poetry trouve." +} + +# Verification du fonctionnement de Poetry +try { + $poetryVersion = & "$poetryPath\poetry.exe" --version + Write-Log "Poetry est operationnel : $poetryVersion" +} catch { + Write-Log "ERREUR : Impossible de verifier la commande 'poetry' apres installation." +} + +# ========================================== +# Installation des dependances du projet +# ========================================== +Write-Log "=== Installation des dependances Python via Poetry ===" + +if (Test-Path $projectDir) { + Set-Location $projectDir + try { + # Contournement de l'erreur Windows Credential Manager / WinRM + Write-Log "Desactivation du keyring pour Poetry..." + & "$poetryPath\poetry.exe" config keyring.enabled false + + # Installation des dépendances sans root + & "$poetryPath\poetry.exe" install --no-root + Write-Log "Dependances du projet installees avec succes." + } catch { + Write-Error "Echec de l'installation des dependances : $_" + Write-Log "ERREUR lors de 'poetry install' : $_" + exit 1 + } +} else { + Write-Warning "Dossier projet $projectDir introuvable pour lancer 'poetry install'." + Write-Log "AVERTISSEMENT : Dossier $projectDir introuvable." +} + +Write-Log "=== Fin de la configuration de pysnapcap ===" diff --git a/template/http/s4_dotNet.ps1 b/template/http/s4_dotNet.ps1 new file mode 100644 index 0000000..50fb990 --- /dev/null +++ b/template/http/s4_dotNet.ps1 @@ -0,0 +1,86 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +function Write-Log { + param ([string]$Message) + "$Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +# Logs initiaux +Write-Log "=== Configuration et installation de .NET Framework 3.5 ===" +Write-Host "=== Configuration et installation de .NET Framework 3.5 ===" -ForegroundColor Cyan + +# 1. Verification si .NET 3.5 est deja installe +$net35Status = Get-WindowsOptionalFeature -Online -FeatureName "NetFx3" -ErrorAction SilentlyContinue + +if ($net35Status -and $net35Status.State -eq "Enabled") { + Write-Log ".NET Framework 3.5 est deja active sur cette machine." + Write-Host ".NET Framework 3.5 est deja active." -ForegroundColor Green + exit 0 +} + +# 2. Recherche precise d'un fichier .cab ou du dossier sxs contenant les sources .NET 3.5 +$cdDrives = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -ne $null -or $_.Used -ne $null } +$validSxsSource = $null + +foreach ($drive in $cdDrives) { + $pathsToTest = @( + "$($drive.Name):\sources\sxs", + "$($drive.Name):\install\sxs", + "$($drive.Name):\install" + ) + + foreach ($path in $pathsToTest) { + if (Test-Path $path) { + # Verification qu'un fichier cab lie a NetFx3 existe bien dans le dossier + $cabFile = Get-ChildItem -Path $path -Filter "*netfx3*.cab" -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($cabFile) { + $validSxsSource = $path + break + } + } + } + if ($validSxsSource) { break } +} + +# 3. Tentative d'installation (Source locale puis Windows Update) +$installedSuccessfully = $false + +if ($validSxsSource) { + Write-Log "Fichiers sources .NET 3.5 trouves dans : $validSxsSource" + Write-Host "Installation depuis la source locale ($validSxsSource)..." -ForegroundColor Yellow + + try { + Enable-WindowsOptionalFeature -Online -FeatureName "NetFx3" -Source $validSxsSource -LimitAccess -All -NoRestart -ErrorAction Stop | Out-Null + $installedSuccessfully = $true + } catch { + Write-Warning "L'installation hors-ligne a echoue. Tentative via Windows Update..." + Write-Log "AVERTISSEMENT : Echec de l'installation hors-ligne depuis $validSxsSource : $_" + } +} + +# Fallback sur Windows Update / DISM en ligne si pas de source locale valide ou en cas d'échec +if (-not $installedSuccessfully) { + Write-Log "Tentative d'installation de .NET 3.5 via Windows Update..." + Write-Host "Installation via Windows Update en cours..." -ForegroundColor Yellow + + try { + # Utilisation de DISM directement pour autoriser le telechargement en ligne + $dismResult = DISM.exe /Online /Enable-Feature /FeatureName:NetFx3 /All /Quiet /NoRestart + if ($LASTEXITCODE -eq 0) { + $installedSuccessfully = $true + } else { + throw "DISM a retourne le code d'erreur $LASTEXITCODE" + } + } catch { + Write-Error "Echec de l'installation de .NET Framework 3.5 : $_" + Write-Log "ERREUR lors de l'installation de .NET 3.5 : $_" + exit 1 + } +} + +if ($installedSuccessfully) { + Write-Log ".NET Framework 3.5 a ete installe avec succes." + Write-Host ".NET Framework 3.5 installe avec succes." -ForegroundColor Green +} + +Write-Log "=== Fin de l'installation de .NET Framework 3.5 ===" diff --git a/template/http/s5_com0com.ps1 b/template/http/s5_com0com.ps1 new file mode 100644 index 0000000..bbf7ddc --- /dev/null +++ b/template/http/s5_com0com.ps1 @@ -0,0 +1,132 @@ +#Requires -RunAsAdministrator + +Set-ExecutionPolicy Bypass -Scope Process -Force +$ErrorActionPreference = "Stop" +$LogFile = "C:\install.log" + +function Write-Log($msg) { + $time = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + Add-Content -Path $LogFile -Value "$time - $msg" -Encoding UTF8 + Write-Host "$msg" -ForegroundColor Cyan +} + +Write-Log "==========================================" +Write-Log "Debut de l installation silencieuse com0com" + +# 1. Activation de TESTSIGNING +Write-Log "Verification de TESTSIGNING..." +$bcd = bcdedit.exe /enum '{current}' +if (($bcd -join "`n") -notmatch "testsigning\s+Yes") { + Write-Log "Activation TESTSIGNING..." + bcdedit.exe /set testsigning on | Out-Null + Write-Log "ATTENTION: Un redemarrage est requis si TESTSIGNING vient d etre active." +} + +# 2. Localisation de setup.exe +Write-Log "Recherche de setup.exe..." +$setupExe = $null + +$drives = Get-PSDrive -PSProvider FileSystem +foreach ($drive in $drives) { + $targetPath = Join-Path $drive.Root "install\setup.exe" + if (Test-Path $targetPath) { + $setupExe = Get-Item $targetPath + break + } +} + +if (-not $setupExe) { + $setupExe = Get-ChildItem -Path "C:\install", "D:\install" -Filter "setup.exe" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 +} + +if ($setupExe) { + Write-Log "Installeur trouve : $($setupExe.FullName)" + + # 3. Installation silencieuse de setup.exe + Write-Log "Lancement de l installeur silencieux..." + $proc = Start-Process -FilePath $setupExe.FullName -ArgumentList "/S" -Wait -PassThru + Write-Log "Code de retour installeur : $($proc.ExitCode)" +} else { + Write-Log "ERREUR : setup.exe introuvable." + exit 1 +} + +# 4. Localisation des fichiers installés +$setupc = "C:\Program Files (x86)\com0com\setupc.exe" +if (-not (Test-Path $setupc)) { + $setupc = "C:\Program Files\com0com\setupc.exe" +} + +if (Test-Path $setupc) { + $workDir = Split-Path $setupc -Parent + $infFile = Join-Path $workDir "com0com.inf" + + # 5. Extraction et ajout de TOUS les certificats signatures trouvés dans le dossier com0com + Write-Log "Extraction des certificats depuis le dossier : $workDir" + + # Recherche de tous les fichiers susceptibles d'être signés (.sys, .cat, .dll, .exe, .cer, .crt) + $filesToScan = Get-ChildItem -Path $workDir -Recurse -Include "*.sys", "*.cat", "*.dll", "*.exe", "*.cer", "*.crt" + + $importedThumbprints = @() + + foreach ($file in $filesToScan) { + # Si c'est déjà un fichier certificat (.cer / .crt) + if ($file.Extension -match "\.(cer|crt)$") { + Write-Log "Fichier certificat brut trouve : $($file.Name)" + certutil.exe -addstore "TrustedPublisher" $file.FullName | Out-Null + certutil.exe -addstore "Root" $file.FullName | Out-Null + Write-Log "Certificat $($file.Name) importe dans TrustedPublisher et Root." + continue + } + + # Si c'est un fichier signé (.sys, .cat, .dll, .exe) + $sig = Get-AuthenticodeSignature -FilePath $file.FullName + if ($sig.SignerCertificate) { + $cert = $sig.SignerCertificate + + # Évite d'importer plusieurs fois le même certificat s'il signe plusieurs fichiers + if ($importedThumbprints -notcontains $cert.Thumbprint) { + $certPath = Join-Path $env:TEMP "$($cert.Thumbprint).cer" + [System.IO.File]::WriteAllBytes($certPath, $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)) + + certutil.exe -addstore "TrustedPublisher" $certPath | Out-Null + certutil.exe -addstore "Root" $certPath | Out-Null + + $importedThumbprints += $cert.Thumbprint + Write-Log "Certificat extrait et importe : '$($cert.Subject)' (Thumbprint: $($cert.Thumbprint))" + + Remove-Item $certPath -Force -ErrorAction SilentlyContinue + } + } + } + + # 6. Enregistrement du pilote via PnPUtil + if (Test-Path $infFile) { + Write-Log "Enregistrement du pilote com0com.inf dans le magasin Windows..." + pnputil.exe /add-driver "$infFile" /install | Out-Null + } + + # 7. Création des ports COM30 et COM31 + Write-Log "Creation des ports COM30 et COM31..." + + # Fichier vide pour rediriger STDIN afin de parer tout blocage d'attente d'entrée + $nullFile = Join-Path$env:TEMP "stdin_null.txt" + New-Item -Path $nullFile -ItemType File -Force | Out-Null + + $p = Start-Process -FilePath$setupc ` + -ArgumentList "install PortName=COM30 PortName=COM31" ` + -WorkingDirectory $workDir ` + -RedirectStandardInput $nullFile ` + -NoNewWindow ` + -Wait ` + -PassThru + + Write-Log "Code de retour setupc : $($p.ExitCode)" + + Remove-Item $nullFile -Force -ErrorAction SilentlyContinue +} else { + Write-Log "ERREUR : setupc.exe est introuvable." + exit 1 +} + +Write-Log "Fin du traitement." diff --git a/template/http/s6_tasks.ps1 b/template/http/s6_tasks.ps1 new file mode 100644 index 0000000..14e96f2 --- /dev/null +++ b/template/http/s6_tasks.ps1 @@ -0,0 +1,242 @@ +#Requires -RunAsAdministrator + +Set-ExecutionPolicy Bypass -Scope Process -Force +$ErrorActionPreference = "Stop" + +function Write-Log { + param ([string]$Message) + $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + "$timestamp - $Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +Write-Log "=== Recherche du lecteur et copie des scripts Beweis ===" +Write-Host "=== Configuration et copie des scripts Beweis ===" -ForegroundColor Cyan + +# 1. Detection automatique du lecteur CD / Clé USB contenant le dossier "install" +$cdDrive = Get-PSDrive -PSProvider FileSystem | Where-Object { + Test-Path (Join-Path $_.Root "install") +} | Select-Object -First 1 + +if (-not $cdDrive) { + Write-Error "Dossier 'install' introuvable sur les lecteurs de disque." + Write-Log "ERREUR : Dossier 'install' introuvable sur les lecteurs de disque." + exit 1 +} + +$installDir = Join-Path "$($cdDrive.Name):\" "install" +Write-Log "Dossier d'installation trouve : $installDir" + +$destinationDir = "C:\ProgramData\beWeis\" +if (-not (Test-Path $destinationDir)) { + New-Item -Path $destinationDir -ItemType Directory -Force | Out-Null + Write-Log "Dossier $destinationDir cree." +} + +# 2. Copie des fichiers start_beweapon.ps1 / start.ps1 et test.ps1 +$filesToCopy = @("start_beweapon.ps1", "start.ps1", "test.ps1") + +foreach ($fileName in $filesToCopy) { + $sourceFile = Join-Path $installDir $fileName + + if (Test-Path $sourceFile) { + try { + Copy-Item -Path $sourceFile -Destination $destinationDir -Force -ErrorAction Stop + Write-Log "Fichier $fileName copie avec succes dans $destinationDir" + Write-Host "Copie : $fileName -> $destinationDir" -ForegroundColor Green + } catch { + Write-Error "Echec de la copie de $fileName : $_" + Write-Log "ERREUR lors de la copie de $fileName : $_" + } + } +} + +# ========================================================================= +# Installation automatique des pilotes système (Drivers INF, EXE, MSI) +# ========================================================================= +Write-Log "=== Installation des pilotes systeme (Drivers) ===" +Write-Host "Recherche et installation des pilotes..." -ForegroundColor Cyan + +$driversDir = Join-Path $installDir "drivers" +if (-not (Test-Path $driversDir)) { + $driversDir = $installDir +} + +try { + $infFiles = Get-ChildItem -Path $driversDir -Filter "*.inf" -Recurse -ErrorAction SilentlyContinue + + if ($infFiles) { + foreach ($inf in $infFiles) { + Write-Log "Traitement du fichier INF : $($inf.FullName)" + + $catFiles = Get-ChildItem -Path $inf.DirectoryName -Filter "*.cat" -ErrorAction SilentlyContinue + foreach ($cat in $catFiles) { + $sig = Get-AuthenticodeSignature -FilePath $cat.FullName + if ($sig.SignerCertificate) { + $tempCert = "C:\Windows\Temp\driver_cert.cer" + [System.IO.File]::WriteAllBytes($tempCert, $sig.SignerCertificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)) + certutil.exe -addstore "TrustedPublisher" $tempCert | Out-Null + certutil.exe -addstore "Root" $tempCert | Out-Null + Remove-Item $tempCert -Force -ErrorAction SilentlyContinue + } + } + + & pnputil.exe /add-driver "$($inf.FullName)" /install | Out-Null + Write-Log "pnputil traite : $($inf.Name)" + } + } + + $exeDrivers = Get-ChildItem -Path $driversDir -Include "*driver*.exe", "*dpinst*.exe" -File -Recurse -ErrorAction SilentlyContinue + foreach ($exe in $exeDrivers) { + if ($exe.FullName -ne (Join-Path $installDir "setup.exe")) { + Write-Log "Lancement de l'installeur de pilote : $($exe.FullName)" + Start-Process -FilePath $exe.FullName -ArgumentList "/S", "/q", "/silent" -Wait -NoNewWindow -ErrorAction SilentlyContinue + } + } + Write-Host "Installation des pilotes systeme terminee." -ForegroundColor Green +} catch { + Write-Log "AVERTISSEMENT lors de l'installation des pilotes systeme : $_" +} + +# ========================================================================= +# Installation du Driver Appium Windows & WinAppDriver +# ========================================================================= +Write-Log "=== Installation du Driver Appium Windows & WinAppDriver ===" +Write-Host "Configuration des drivers Appium Windows & WinAppDriver..." -ForegroundColor Cyan + +try { + # 1. Activation du Mode Developpeur Windows (obligatoire pour WinAppDriver) + Write-Log "Activation du Mode Developpeur Windows..." + $devModeReg = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" + if (-not (Test-Path $devModeReg)) { New-Item -Path $devModeReg -Force | Out-Null } + Set-ItemProperty -Path $devModeReg -Name "AllowDevelopmentWithoutDevLicense" -Value 1 -Type DWord -Force + + # 2. Installation du driver Appium Windows + Write-Log "Installation du driver Appium Windows..." + Write-Host "Installation du driver Appium Windows..." -ForegroundColor Yellow + Start-Process -FilePath "npx.cmd" -ArgumentList "appium driver install windows" -Wait -NoNewWindow -ErrorAction SilentlyContinue + + # 3. Téléchargement et Installation de WinAppDriver (WindowsApplicationDriver.msi) + $wadPath = "C:\Program Files (x86)\Windows Application Driver\WinAppDriver.exe" + + if (-not (Test-Path $wadPath)) { + Write-Log "WinAppDriver non trouve. Installation en cours..." + + # Verification si le fichier .msi est deja sur le disque d'installation + $localWadMsi = Get-ChildItem -Path $installDir -Filter "*WindowsApplicationDriver*.msi" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 + + $msiPath = "" + if ($localWadMsi) { + $msiPath = $localWadMsi.FullName + Write-Log "Utilisation de l'installeur local WinAppDriver : $msiPath" + } else { + # Telechargement depuis le depot officiel Microsoft GitHub + $msiPath = "C:\Windows\Temp\WindowsApplicationDriver.msi" + $downloadUrl = "https://github.com/microsoft/WinAppDriver/releases/download/v1.2.1/WindowsApplicationDriver.msi" + + Write-Host "Telechargement de WinAppDriver depuis GitHub..." -ForegroundColor Yellow + Write-Log "Telechargement de WinAppDriver ($downloadUrl)..." + + # Configuration du protocole SSL/TLS et User-Agent pour eviter l'erreur 503 / Reset Connection + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 + + $webClient = New-Object System.Net.WebClient + $webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)") + $webClient.DownloadFile($downloadUrl, $msiPath) + } + + # Installation silencieuse via msiexec + if (Test-Path $msiPath) { + Write-Log "Lancement de l'installation silencieuse de WinAppDriver..." + Write-Host "Installation de WinAppDriver.msi en cours..." -ForegroundColor Yellow + + $msiProcess = Start-Process -FilePath "msiexec.exe" -ArgumentList "/i `"$msiPath`" /quiet /qn /norestart" -Wait -PassThru -NoNewWindow + Write-Log "Code de retour msiexec WinAppDriver : $($msiProcess.ExitCode)" + } else { + Write-Log "ERREUR : Le fichier MSI de WinAppDriver n'a pas pu etre recupere." + } + } + + # Verification finale de la presence de WinAppDriver.exe + if (Test-Path $wadPath) { + Write-Host "WinAppDriver s'est installe avec succes !" -ForegroundColor Green + Write-Log "WinAppDriver est operationnel dans : $wadPath" + } else { + Write-Log "AVERTISSEMENT : L'installation s'est terminee mais WinAppDriver.exe n'est pas detectable." + } + +} catch { + Write-Log "ERREUR lors de l'installation de WinAppDriver : $_" + Write-Host "Erreur lors de la configuration de WinAppDriver : $_" -ForegroundColor Red +} + +# ========================================================================= +# Création de la Tâche Planifiée Windows +# ========================================================================= +Write-Log "=== Creation de la tache planifiee StartBeweapon ===" +Write-Host "Creation de la tache planifiee..." -ForegroundColor Cyan + +$taskName = "StartBeweapon" + +$scriptToRun = Join-Path $destinationDir "start_beweapon.ps1" +if (-not (Test-Path $scriptToRun)) { + $scriptToRun = Join-Path $destinationDir "start.ps1" +} + +if (Test-Path $scriptToRun) { + try { + $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptToRun`"" + + $trigger = New-ScheduledTaskTrigger -AtLogOn + $trigger.Delay = 'PT30S' + + $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name + $principal = New-ScheduledTaskPrincipal -UserId $currentUser -RunLevel Highest + + $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable + + Register-ScheduledTask -TaskName $taskName ` + -Action $action ` + -Trigger $trigger ` + -Principal $principal ` + -Settings $settings ` + -Force -ErrorAction Stop | Out-Null + + Write-Log "Tache planifiee '$taskName' creee avec succes pour$currentUser." + Write-Host "Tache planifiee '$taskName' creee avec succes." -ForegroundColor Green + } catch { + Write-Error "Echec de la creation de la tache planifiee : $_" + Write-Log "ERREUR lors de la creation de la tache planifiee : $_" + exit 1 + } +} else { + Write-Error "Impossible de creer la tache planifiee : le script de demarrage est introuvable." + Write-Log "ERREUR : Script de demarrage introuvable dans $destinationDir." + exit 1 +} + +# Liste des lettres à démonter +$drives = @("D", "E", "F") +$shell = New-Object -ComObject Shell.Application + +foreach ($drive in $drives) { + try { + $shell.Namespace(17).ParseName("${drive}:").InvokeVerb("Eject") + Write-Host "Lecteur ${drive}: éjecté avec succès." -ForegroundColor Green + } catch { + Write-Host "Impossible d'éjecter le lecteur ${drive}:" -ForegroundColor Red + } +} +# Liste des lettres à démonter +$drives = @("D", "E", "F") +$shell = New-Object -ComObject Shell.Application + +foreach ($drive in $drives) { + try { + $shell.Namespace(17).ParseName("${drive}:").InvokeVerb("Eject") + Write-Host "Lecteur ${drive}: éjecté avec succès." -ForegroundColor Green + } catch { + Write-Host "Impossible d'éjecter le lecteur ${drive}:" -ForegroundColor Red + } +} + +Write-Log "=== Fin de l'operation ===" diff --git a/template/http/s7_CDremove.ps1 b/template/http/s7_CDremove.ps1 new file mode 100644 index 0000000..7840494 --- /dev/null +++ b/template/http/s7_CDremove.ps1 @@ -0,0 +1,63 @@ +Set-ExecutionPolicy Bypass -Scope Process -Force + +function Write-Log { + param ([string]$Message) + "$Message" | Out-File -FilePath "C:\install.log" -Append -Encoding utf8 +} + +Write-Log "=== Démonstration et éjection de tous les lecteurs CD/DVD ===" +Write-Host "=== Démonstration et éjection des lecteurs CD/DVD ===" -ForegroundColor Cyan + +# Initialisation de l'objet COM Shell pour l'éjection des médias +$shell = New-Object -ComObject Shell.Application + +# Récupération de tous les lecteurs de type CD-ROM / DVD-ROM +$cdDrives = Get-CimInstance -ClassName Win32_CDROMDrive + +if (-not $cdDrives) { + Write-Log "Aucun lecteur CD/DVD détecté sur la machine." + Write-Host "Aucun lecteur CD/DVD trouvé." -ForegroundColor Yellow + exit 0 +} + +foreach ($drive in $cdDrives) { + $driveLetter = $drive.Drive + if ($driveLetter) { + Write-Log "Traitement du lecteur CD : $driveLetter" + Write-Host "Démontage du lecteur $driveLetter..." -ForegroundColor Yellow + + # 1. Éjection logicielle du média (ISO) + try { + $driveFolder = $shell.NameSpace($driveLetter) + if ($driveFolder) { + # Commande 'Eject' (0x22 dans les verbes Shell) + $driveFolder.Self.InvokeVerb("Eject") + Write-Log "Éjection logicielle réussie pour $driveLetter" + } + } catch { + Write-Log "Avertissement lors de l'éjection de $driveLetter : $_" + } + + # 2. Suppression de la lettre d'accès (démontage du lecteur) + try { + $cleanLetter = $driveLetter.Replace(":", "") + Get-Partition -DriveLetter $cleanLetter -ErrorAction SilentlyContinue | ForEach-Object { + Remove-PartitionAccessPath -DiskNumber $_.DiskNumber -PartitionNumber $_.PartitionNumber -AccessPath "$driveLetter\" -ErrorAction Stop + } + Write-Log "Lettre d'accès $driveLetter supprimée avec succès." + Write-Host "Lecteur $driveLetter démonté avec succès." -ForegroundColor Green + } catch { + # Si Remove-PartitionAccessPath échoue sur certains lecteurs virtuels, fallback avec mountvol + try { + mountvol.exe "$driveLetter" /d + Write-Log "Lettre $driveLetter démontée via mountvol." + Write-Host "Lecteur $driveLetter démonté via mountvol." -ForegroundColor Green + } catch { + Write-Error "Impossible de supprimer la lettre $driveLetter : $_" + Write-Log "ERREUR suppression lettre $driveLetter : $_" + } + } + } +} + +Write-Log "=== Fin du démontage des lecteurs CD ===" diff --git a/template/http/windows-scripts/generalize.ps1 b/template/http/windows-scripts/generalize.ps1 new file mode 100644 index 0000000..298641f --- /dev/null +++ b/template/http/windows-scripts/generalize.ps1 @@ -0,0 +1,71 @@ +Set-StrictMode -Version Latest +$ProgressPreference = 'SilentlyContinue' +$ErrorActionPreference = 'Stop' +trap { + Write-Host "ERROR: $_" + ($_.ScriptStackTrace -split '\r?\n') -replace '^(.*)$', 'ERROR: $1' | Write-Host + ($_.Exception.ToString() -split '\r?\n') -replace '^(.*)$', 'ERROR EXCEPTION: $1' | Write-Host + Exit 1 +} + +# remove the sshd host keys. +Write-Host 'Removing the sshd host keys...' +Remove-Item -Force C:\ProgramData\ssh\ssh_host_* + +# reset cloudbase-init. +Write-Host 'Resetting cloudbase-init...' +Remove-Item 'C:\Program Files\Cloudbase Solutions\Cloudbase-Init\log\*.log' + +# create the sysprep unattended.xml file. +$unattendPath = 'C:/Windows/System32/Sysprep/provision-generalize-unattended.xml' +# see https://github.com/rgl/vagrant-windows-sysprep/blob/master/lib/vagrant-windows-sysprep/unattend.xml +Set-Content -Encoding UTF8 -Path $unattendPath -NoNewLine -Value @" +<?xml version="1.0" encoding="utf-8"?> +<!-- + sysprep copies this file to C:\Windows\Panther\unattend.xml + the logs are stored at C:\Windows\Panther\setupact.log +--> +<unattend xmlns="urn:schemas-microsoft-com:unattend"> + <settings pass="generalize"> + <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <SkipRearm>1</SkipRearm> + </component> + <component name="Microsoft-Windows-PnpSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <PersistAllDeviceInstalls>true</PersistAllDeviceInstalls> + <DoNotCleanUpNonPresentDevices>true</DoNotCleanUpNonPresentDevices> + </component> + </settings> + <settings pass="oobeSystem"> + <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <InputLocale>en-US</InputLocale> + <SystemLocale>en-US</SystemLocale> + <UILanguage>en-US</UILanguage> + <UserLocale>en-US</UserLocale> + </component> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <OOBE> + <HideEULAPage>true</HideEULAPage> + <HideLocalAccountScreen>true</HideLocalAccountScreen> + <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen> + <HideOnlineAccountScreens>true</HideOnlineAccountScreens> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <NetworkLocation>Home</NetworkLocation> + <ProtectYourPC>1</ProtectYourPC> + </OOBE> + </component> + </settings> +</unattend> +"@ + +# sysprep the machine. +# see https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-setup-states?view=windows-10 +Write-Host 'Syspreping the machine...' +C:/Windows/System32/Sysprep/Sysprep.exe ` + /mode:vm ` + /oobe ` + /generalize ` + /quiet ` + /quit ` + "/unattend:$unattendPath" ` + | Out-String -Stream + diff --git a/template/http/windows-scripts/setup.ps1 b/template/http/windows-scripts/setup.ps1 new file mode 100644 index 0000000..a3de9c1 --- /dev/null +++ b/template/http/windows-scripts/setup.ps1 @@ -0,0 +1,38 @@ +$ErrorActionPreference = "Stop" + +# Switch network connection to private mode +# Required for WinRM firewall rules +$profile = Get-NetConnectionProfile +Set-NetConnectionProfile -Name $profile.Name -NetworkCategory Private + +# Enable WinRM service +winrm quickconfig -quiet +winrm set winrm/config/service '@{AllowUnencrypted="true"}' +winrm set winrm/config/service/auth '@{Basic="true"}' + +# Disable IPv6 because it leads to problems with proxmox terraform +Get-NetAdapter | foreach { Disable-NetAdapterBinding -InterfaceAlias $_.Name -ComponentID ms_tcpip6 } + +# Reset auto logon count +# https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-autologon-logoncount#logoncount-known-issue +Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoLogonCount -Value 0 + +# Run a custom installer script if there is one +$customInstaller = Join-Path $PSScriptRoot "custom\custom.ps1" +if (Test-Path $customInstaller) { + & $customInstaller +} + +# Add French Keyboard +Set-WinUserLanguageList fr-FR,en-US -Force + +# Set time zone to Europe/Paris +Set-TimeZone -Id "Romance Standard Time" + +# Allow Remote Desktop +Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0 +Enable-NetFirewallRule -DisplayGroup "Remote Desktop" + +# Allow script execution +Set-ExecutionPolicy -ExecutionPolicy Bypass + diff --git a/template/http/windows/Autounattend-win11.xml.pkrtpl b/template/http/windows/Autounattend-win11.xml.pkrtpl new file mode 100644 index 0000000..4f88b58 --- /dev/null +++ b/template/http/windows/Autounattend-win11.xml.pkrtpl @@ -0,0 +1,226 @@ +<?xml version="1.0" encoding="utf-8"?> +<unattend xmlns="urn:schemas-microsoft-com:unattend"> + <settings pass="windowsPE"> + <component name="Microsoft-Windows-PnpCustomizationsWinPE" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"> + + <!-- + This makes the VirtIO drivers available to Windows, assuming that + the VirtIO driver disk at https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso + (see https://docs.fedoraproject.org/en-US/quick-docs/creating-windows-virtual-machines-using-virtio-drivers/index.html#virtio-win-direct-downloads) + is available as drive D: + --> + <DriverPaths> + <PathAndCredentials wcm:action="add" wcm:keyValue="2"> + <Path>D:\viostor\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="3"> + <Path>D:\NetKVM\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="4"> + <Path>D:\Balloon\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="5"> + <Path>D:\pvpanic\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="6"> + <Path>D:\qemupciserial\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="7"> + <Path>D:\qxldod\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="8"> + <Path>D:\vioinput\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="9"> + <Path>D:\viorng\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="10"> + <Path>D:\vioscsi\${driver_version}\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="11"> + <Path>D:\vioserial\${driver_version}\amd64</Path> + </PathAndCredentials> + </DriverPaths> + </component> + <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <SetupUILanguage> + <UILanguage>${windows_language}</UILanguage> + </SetupUILanguage> + <InputLocale>${windows_input_language}</InputLocale> + <SystemLocale>${windows_language}</SystemLocale> + <UILanguage>${windows_language}</UILanguage> + <UserLocale>${windows_language}</UserLocale> + </component> + <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <!-- TPM 2.0 and SecureBoot bypass --> + <RunSynchronous> + <RunSynchronousCommand wcm:action="add"> + <Order>1</Order> + <Description>BypassTPMCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassTPMCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + <RunSynchronousCommand wcm:action="add"> + <Order>2</Order> + <Description>BypassSecureBootCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassSecureBootCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + <RunSynchronousCommand wcm:action="add"> + <Order>3</Order> + <Description>BypassRAMCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassRAMCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + </RunSynchronous> + <DiskConfiguration> + <Disk wcm:action="add"> + <CreatePartitions> + <CreatePartition wcm:action="add"> + <Order>1</Order> + <Type>Primary</Type> + <Size>100</Size> + </CreatePartition> + <CreatePartition wcm:action="add"> + <Order>2</Order> + <Type>Primary</Type> + <Extend>true</Extend> + </CreatePartition> + </CreatePartitions> + <ModifyPartitions> + <ModifyPartition wcm:action="add"> + <Order>1</Order> + <PartitionID>1</PartitionID> + <Label>System Reserved</Label> + <Format>NTFS</Format> + <Active>true</Active> + </ModifyPartition> + <ModifyPartition wcm:action="add"> + <Extend>false</Extend> + <Format>NTFS</Format> + <Letter>C</Letter> + <Order>2</Order> + <PartitionID>2</PartitionID> + <Label>Windows</Label> + </ModifyPartition> + </ModifyPartitions> + <DiskID>0</DiskID> + <WillWipeDisk>true</WillWipeDisk> + <!-- <MBR>true</MBR> --> + </Disk> + <WillShowUI>OnError</WillShowUI> + </DiskConfiguration> + <UserData> + <AcceptEula>true</AcceptEula> + <FullName>${winrm_username}</FullName> + <Organization>Administrators</Organization> + <ProductKey> + <WillShowUI>Never</WillShowUI> + </ProductKey> + </UserData> + <ImageInstall> + <OSImage> + <InstallTo> + <DiskID>0</DiskID> + <PartitionID>2</PartitionID> + </InstallTo> + <WillShowUI>OnError</WillShowUI> + <InstallToAvailablePartition>false</InstallToAvailablePartition> + <InstallFrom> + <MetaData wcm:action="add"> + <Key>/IMAGE/NAME</Key> + <Value>${windows_edition}</Value> + </MetaData> + </InstallFrom> + </OSImage> + </ImageInstall> + </component> + </settings> + <settings pass="specialize"> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <ComputerName>*</ComputerName> + <TimeZone>UTC</TimeZone> + </component> + <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <fDenyTSConnections>false</fDenyTSConnections> + </component> + <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <FirewallGroups> + <FirewallGroup wcm:action="add" wcm:keyValue="RemoteDesktop"> + <Active>true</Active> + <Group>Remote Desktop</Group> + <Profile>all</Profile> + </FirewallGroup> + </FirewallGroups> + </component> + <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <UserAuthentication>0</UserAuthentication> + </component> + </settings> + <settings pass="oobeSystem"> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <AutoLogon> + <Enabled>true</Enabled> + <Username>${winrm_username}</Username> + <Password> + <Value>${winrm_password}</Value> + <PlainText>true</PlainText> + </Password> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <!-- Enable WinRM service --> + <CommandLine>powershell -ExecutionPolicy Bypass -File F:\setup.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <!-- Configure Remote execution for ansible --> + <Order>2</Order> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible-documentation/refs/heads/devel/examples/scripts/ConfigureRemotingForAnsible.ps1'))"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>3</Order> + <!-- Install Proxmox guest-agent --> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "D:\guest-agent\qemu-ga-x86_64.msi /quiet"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>4</Order> + <!-- Generalize --> + <CommandLine>powershell -ExecutionPolicy Bypass -File F:\generalize.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + </FirstLogonCommands> + <OOBE> + <ProtectYourPC>3</ProtectYourPC> + <HideEULAPage>true</HideEULAPage> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <SkipUserOOBE>true</SkipUserOOBE> + <SkipMachineOOBE>true</SkipMachineOOBE> + </OOBE> + <UserAccounts> + <LocalAccounts> + <LocalAccount wcm:action="add"> + <Name>${winrm_username}</Name> + <Group>Administrators</Group> + <Password> + <Value>${winrm_password}</Value> + <PlainText>true</PlainText> + </Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + </component> + </settings> + <settings pass="offlineServicing"> + <component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <EnableLUA>false</EnableLUA> + </component> + </settings> +</unattend> \ No newline at end of file diff --git a/template/iso/Autounattend.xml b/template/iso/Autounattend.xml new file mode 100644 index 0000000..dcdaa06 --- /dev/null +++ b/template/iso/Autounattend.xml @@ -0,0 +1,226 @@ +<?xml version="1.0" encoding="utf-8"?> +<unattend xmlns="urn:schemas-microsoft-com:unattend"> + <settings pass="windowsPE"> + <component name="Microsoft-Windows-PnpCustomizationsWinPE" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"> + + <!-- + This makes the VirtIO drivers available to Windows, assuming that + the VirtIO driver disk at https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/stable-virtio/virtio-win.iso + (see https://docs.fedoraproject.org/en-US/quick-docs/creating-windows-virtual-machines-using-virtio-drivers/index.html#virtio-win-direct-downloads) + is available as drive D: + --> + <DriverPaths> + <PathAndCredentials wcm:action="add" wcm:keyValue="2"> + <Path>D:\viostor\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="3"> + <Path>D:\NetKVM\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="4"> + <Path>D:\Balloon\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="5"> + <Path>D:\pvpanic\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="6"> + <Path>D:\qemupciserial\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="7"> + <Path>D:\qxldod\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="8"> + <Path>D:\vioinput\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="9"> + <Path>D:\viorng\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="10"> + <Path>D:\vioscsi\w11\amd64</Path> + </PathAndCredentials> + + <PathAndCredentials wcm:action="add" wcm:keyValue="11"> + <Path>D:\vioserial\w11\amd64</Path> + </PathAndCredentials> + </DriverPaths> + </component> + <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <SetupUILanguage> + <UILanguage>fr-FR</UILanguage> + </SetupUILanguage> + <InputLocale>fr-FR</InputLocale> + <SystemLocale>fr-FR</SystemLocale> + <UILanguage>fr-FR</UILanguage> + <UserLocale>fr-FR</UserLocale> + </component> + <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <!-- TPM 2.0 and SecureBoot bypass --> + <RunSynchronous> + <RunSynchronousCommand wcm:action="add"> + <Order>1</Order> + <Description>BypassTPMCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassTPMCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + <RunSynchronousCommand wcm:action="add"> + <Order>2</Order> + <Description>BypassSecureBootCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassSecureBootCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + <RunSynchronousCommand wcm:action="add"> + <Order>3</Order> + <Description>BypassRAMCheck</Description> + <Path>cmd /c reg add "HKLM\SYSTEM\Setup\LabConfig" /v "BypassRAMCheck" /t REG_DWORD /d 1</Path> + </RunSynchronousCommand> + </RunSynchronous> + <DiskConfiguration> + <Disk wcm:action="add"> + <CreatePartitions> + <CreatePartition wcm:action="add"> + <Order>1</Order> + <Type>Primary</Type> + <Size>100</Size> + </CreatePartition> + <CreatePartition wcm:action="add"> + <Order>2</Order> + <Type>Primary</Type> + <Extend>true</Extend> + </CreatePartition> + </CreatePartitions> + <ModifyPartitions> + <ModifyPartition wcm:action="add"> + <Order>1</Order> + <PartitionID>1</PartitionID> + <Label>System Reserved</Label> + <Format>NTFS</Format> + <Active>true</Active> + </ModifyPartition> + <ModifyPartition wcm:action="add"> + <Extend>false</Extend> + <Format>NTFS</Format> + <Letter>C</Letter> + <Order>2</Order> + <PartitionID>2</PartitionID> + <Label>Windows</Label> + </ModifyPartition> + </ModifyPartitions> + <DiskID>0</DiskID> + <WillWipeDisk>true</WillWipeDisk> + <!-- <MBR>true</MBR> --> + </Disk> + <WillShowUI>OnError</WillShowUI> + </DiskConfiguration> + <UserData> + <AcceptEula>true</AcceptEula> + <FullName>Installer</FullName> + <Organization>Administrators</Organization> + <ProductKey> + <WillShowUI>Never</WillShowUI> + </ProductKey> + </UserData> + <ImageInstall> + <OSImage> + <InstallTo> + <DiskID>0</DiskID> + <PartitionID>2</PartitionID> + </InstallTo> + <WillShowUI>OnError</WillShowUI> + <InstallToAvailablePartition>false</InstallToAvailablePartition> + <InstallFrom> + <MetaData wcm:action="add"> + <Key>/IMAGE/INDEX</Key> + <Value>6</Value> + </MetaData> + </InstallFrom> + </OSImage> + </ImageInstall> + </component> + </settings> + <settings pass="specialize"> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <ComputerName>*</ComputerName> + <TimeZone>UTC</TimeZone> + </component> + <component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <fDenyTSConnections>false</fDenyTSConnections> + </component> + <component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <FirewallGroups> + <FirewallGroup wcm:action="add" wcm:keyValue="RemoteDesktop"> + <Active>true</Active> + <Group>Remote Desktop</Group> + <Profile>all</Profile> + </FirewallGroup> + </FirewallGroups> + </component> + <component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <UserAuthentication>0</UserAuthentication> + </component> + </settings> + <settings pass="oobeSystem"> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <AutoLogon> + <Enabled>true</Enabled> + <Username>Installer</Username> + <Password> + <Value>Stid_2026-03</Value> + <PlainText>true</PlainText> + </Password> + </AutoLogon> + <FirstLogonCommands> + <SynchronousCommand wcm:action="add"> + <Order>1</Order> + <!-- Enable WinRM service --> + <CommandLine>powershell -ExecutionPolicy Bypass -File E:\setup.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <!-- Configure Remote execution for ansible --> + <Order>2</Order> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/ansible/ansible-documentation/refs/heads/devel/examples/scripts/ConfigureRemotingForAnsible.ps1'))"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>3</Order> + <!-- Install Proxmox guest-agent --> + <CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "D:\guest-agent\qemu-ga-x86_64.msi /passive"</CommandLine> + </SynchronousCommand> + <SynchronousCommand wcm:action="add"> + <Order>4</Order> + <!-- Generalize --> + <CommandLine>powershell -ExecutionPolicy Bypass -File E:\generalize.ps1</CommandLine> + <RequiresUserInput>true</RequiresUserInput> + </SynchronousCommand> + </FirstLogonCommands> + <OOBE> + <ProtectYourPC>3</ProtectYourPC> + <HideEULAPage>true</HideEULAPage> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <SkipUserOOBE>true</SkipUserOOBE> + <SkipMachineOOBE>true</SkipMachineOOBE> + </OOBE> + <UserAccounts> + <LocalAccounts> + <LocalAccount wcm:action="add"> + <Name>Installer</Name> + <Group>Administrators</Group> + <Password> + <Value>Stid_2026-03</Value> + <PlainText>true</PlainText> + </Password> + </LocalAccount> + </LocalAccounts> + </UserAccounts> + </component> + </settings> + <settings pass="offlineServicing"> + <component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <EnableLUA>false</EnableLUA> + </component> + </settings> +</unattend> diff --git a/template/iso/generalize.ps1 b/template/iso/generalize.ps1 new file mode 100644 index 0000000..298641f --- /dev/null +++ b/template/iso/generalize.ps1 @@ -0,0 +1,71 @@ +Set-StrictMode -Version Latest +$ProgressPreference = 'SilentlyContinue' +$ErrorActionPreference = 'Stop' +trap { + Write-Host "ERROR: $_" + ($_.ScriptStackTrace -split '\r?\n') -replace '^(.*)$', 'ERROR: $1' | Write-Host + ($_.Exception.ToString() -split '\r?\n') -replace '^(.*)$', 'ERROR EXCEPTION: $1' | Write-Host + Exit 1 +} + +# remove the sshd host keys. +Write-Host 'Removing the sshd host keys...' +Remove-Item -Force C:\ProgramData\ssh\ssh_host_* + +# reset cloudbase-init. +Write-Host 'Resetting cloudbase-init...' +Remove-Item 'C:\Program Files\Cloudbase Solutions\Cloudbase-Init\log\*.log' + +# create the sysprep unattended.xml file. +$unattendPath = 'C:/Windows/System32/Sysprep/provision-generalize-unattended.xml' +# see https://github.com/rgl/vagrant-windows-sysprep/blob/master/lib/vagrant-windows-sysprep/unattend.xml +Set-Content -Encoding UTF8 -Path $unattendPath -NoNewLine -Value @" +<?xml version="1.0" encoding="utf-8"?> +<!-- + sysprep copies this file to C:\Windows\Panther\unattend.xml + the logs are stored at C:\Windows\Panther\setupact.log +--> +<unattend xmlns="urn:schemas-microsoft-com:unattend"> + <settings pass="generalize"> + <component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <SkipRearm>1</SkipRearm> + </component> + <component name="Microsoft-Windows-PnpSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <PersistAllDeviceInstalls>true</PersistAllDeviceInstalls> + <DoNotCleanUpNonPresentDevices>true</DoNotCleanUpNonPresentDevices> + </component> + </settings> + <settings pass="oobeSystem"> + <component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <InputLocale>en-US</InputLocale> + <SystemLocale>en-US</SystemLocale> + <UILanguage>en-US</UILanguage> + <UserLocale>en-US</UserLocale> + </component> + <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <OOBE> + <HideEULAPage>true</HideEULAPage> + <HideLocalAccountScreen>true</HideLocalAccountScreen> + <HideOEMRegistrationScreen>true</HideOEMRegistrationScreen> + <HideOnlineAccountScreens>true</HideOnlineAccountScreens> + <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> + <NetworkLocation>Home</NetworkLocation> + <ProtectYourPC>1</ProtectYourPC> + </OOBE> + </component> + </settings> +</unattend> +"@ + +# sysprep the machine. +# see https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/windows-setup-states?view=windows-10 +Write-Host 'Syspreping the machine...' +C:/Windows/System32/Sysprep/Sysprep.exe ` + /mode:vm ` + /oobe ` + /generalize ` + /quiet ` + /quit ` + "/unattend:$unattendPath" ` + | Out-String -Stream + diff --git a/template/iso/setup.ps1 b/template/iso/setup.ps1 new file mode 100644 index 0000000..a3de9c1 --- /dev/null +++ b/template/iso/setup.ps1 @@ -0,0 +1,38 @@ +$ErrorActionPreference = "Stop" + +# Switch network connection to private mode +# Required for WinRM firewall rules +$profile = Get-NetConnectionProfile +Set-NetConnectionProfile -Name $profile.Name -NetworkCategory Private + +# Enable WinRM service +winrm quickconfig -quiet +winrm set winrm/config/service '@{AllowUnencrypted="true"}' +winrm set winrm/config/service/auth '@{Basic="true"}' + +# Disable IPv6 because it leads to problems with proxmox terraform +Get-NetAdapter | foreach { Disable-NetAdapterBinding -InterfaceAlias $_.Name -ComponentID ms_tcpip6 } + +# Reset auto logon count +# https://docs.microsoft.com/en-us/windows-hardware/customize/desktop/unattend/microsoft-windows-shell-setup-autologon-logoncount#logoncount-known-issue +Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoLogonCount -Value 0 + +# Run a custom installer script if there is one +$customInstaller = Join-Path $PSScriptRoot "custom\custom.ps1" +if (Test-Path $customInstaller) { + & $customInstaller +} + +# Add French Keyboard +Set-WinUserLanguageList fr-FR,en-US -Force + +# Set time zone to Europe/Paris +Set-TimeZone -Id "Romance Standard Time" + +# Allow Remote Desktop +Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Value 0 +Enable-NetFirewallRule -DisplayGroup "Remote Desktop" + +# Allow script execution +Set-ExecutionPolicy -ExecutionPolicy Bypass + diff --git a/template/plugins.pkr.hcl b/template/plugins.pkr.hcl new file mode 100644 index 0000000..9951b0e --- /dev/null +++ b/template/plugins.pkr.hcl @@ -0,0 +1,9 @@ +packer { + required_plugins { + proxmox = { + # renovate: githubReleaseVar repo=hashicorp/packer-plugin-proxmox + version = "v1.2.3" + source = "github.com/hashicorp/proxmox" + } + } +} \ No newline at end of file diff --git a/template/variables.pkr.hcl b/template/variables.pkr.hcl new file mode 100644 index 0000000..d52ee12 --- /dev/null +++ b/template/variables.pkr.hcl @@ -0,0 +1,373 @@ +variable "vmid" { + description = "The ID used to reference the virtual machine. If not given, the next free ID on the node will be used." + type = number + default = 0 +} + +variable "name" { + description = "The name of the VM within Proxmox." + type = string +} + +variable "description" { + description = "The description of the VM. Shows as the 'Notes' field in the Proxmox GUI." + type = string + default = "" +} + +variable "node" { + description = "The name of the Proxmox Node on which to place the VM." + type = string +} + +variable "pool" { + description = "The resource pool to which the VM will be added." + type = string + default = "" +} + +variable "cpu_type" { + description = "The type of CPU to emulate in the Guest." + type = string + default = "host" +} + +variable "cpu_sockets" { + description = "The number of CPU sockets to allocate to the VM." + type = number + default = 1 +} + +variable "cpu_cores" { + description = "The number of CPU cores per CPU socket to allocate to the VM." + type = number + default = 4 +} + +variable "memory" { + description = "The amount of memory to allocate to the VM in Megabytes." + type = number + default = 8192 +} + +variable "disk_storage_pool" { + description = "The name of the storage pool on which to store the disks." + type = string + default = "local" +} + +variable "disk_size" { + description = "The size of the created disk." + type = string + default = "40G" +} + +variable "disk_format" { + description = "The drive's backing file's data format." + type = string + default = "qcow2" +} + +variable "disk_type" { + description = "The type of disk device to add." + type = string + default = "sata" +} + +variable "disk_cache" { + description = "The drive's cache mode." + type = string + default = "none" +} + +variable "network_adapter" { + description = "Bridge to which the network device should be attached." + type = string + default = "vmbr2" +} + +variable "network_adapter_model" { + description = "Network Card Model." + type = string + default = "virtio" +} + +variable "network_adapter_mac" { + description = "Override the randomly generated MAC Address for the VM." + type = string + default = null +} + +variable "network_adapter_vlan" { + description = "The VLAN tag to apply to packets on this device." + type = number + default = -1 +} + +variable "network_adapter_firewall" { + description = "Whether to enable the Proxmox firewall on this network device." + type = bool + default = false +} + +variable "vga_type" { + description = "The type of display to virtualize." + type = string + default = "qxl" +} + +variable "vga_memory" { + description = "Sets the VGA memory (in MiB)." + type = number + default = 32 +} + +variable "os" { + description = "The operating system." + type = string + default = "l26" +} + +variable "scsi_controller" { + description = "The SCSI controller model to emulate." + type = string + default = "virtio-scsi-pci" +} + +variable "start_at_boot" { + description = "Whether to have the VM startup after the PVE node starts." + type = bool + default = true +} + +variable "qemu_agent" { + description = "Whether to enable the QEMU Guest Agent. qemu-guest-agent daemon must run the in the quest." + type = bool + default = true +} + +variable "bios" { + description = "Set the machine bios." + type = string + default = "seabios" +} + +variable "proxmox_host" { + description = "IP and Port of the Proxmox host." + type = string +} + +variable "proxmox_user" { + description = "Username when authenticating to Proxmox, including the realm." + type = string +} + +variable "proxmox_password" { + description = "Password for the Proxmox user." + type = string + default = "" +} + +variable "proxmox_token" { + description = "Proxmox Token if you are using API Tokens. If both are set, `proxmox_token` takes precedence." + type = string + default = "" +} + +variable "proxmox_insecure_tls" { + description = "Skip validating the certificate." + type = bool + default = false +} + +variable "iso_download" { + description = "Wether to download from iso_url or use the existing iso_file in the iso_storage_pool." + type = bool + default = true +} + +variable "iso_download_pve" { + description = "Download the specified `iso_url` directly from the PVE node." + type = bool + default = false +} + +variable "iso_url" { + description = "URL to the iso file." + type = string +} + +variable "iso_checksum" { + description = "Checksum of the iso file" + type = string +} + +variable "iso_file" { + description = "Name of the iso file" + type = string +} + +variable "iso_storage_pool" { + description = "Storage pool of the iso file" + type = string + default = "local" +} + +variable "iso_unmount" { + description = "Wether to remove the mounted ISO from the template after finishing." + type = bool + default = true +} + +variable "cloud_init" { + description = "Wether to add a Cloud-Init CDROM drive after the virtual machine has been converted to a template." + type = bool + default = true +} + +variable "cloud_init_storage_pool" { + description = "Name of the Proxmox storage pool to store the Cloud-Init CDROM on." + type = string + default = "local" +} + +variable "additional_iso_files" { + description = "Additional ISO files attached to the virtual machine." + type = list(object({ + iso_file = string + iso_url = string + iso_checksum = string + })) + default = [] +} + +variable "additional_cd_files" { + description = "Additional files attached to the virtual machine as iso." + type = list(object({ + type = string + index = number + files = list(string) + })) + default = [] +} + +variable "boot_command" { + description = "The keys to type when the virtual machine is first booted in order to start the OS installer." + type = list(string) +} + +variable "boot_wait" { + description = "The time to wait before typing boot_command." + type = string + default = "10s" +} + +variable "task_timeout" { + description = "The timeout for Promox API operations, e.g. clones" + type = string + default = "5m" +} + +variable "http_directory" { + description = "Path to a directory to serve using an HTTP server." + type = string + default = "./http" +} + +variable "unattended_content" { + description = "Key/Values for the windows unattended cd with the Autounattend.xml file." + type = map(object({ + template = string + vars = map(string) + })) + default = {} +} + +variable "communicator" { + description = "The packer communicator to use" + type = string + default = "ssh" +} + +variable "ssh_username" { + description = "The ssh username to connect to the guest" + type = string + default = "installer" +} + +variable "ssh_password" { + description = "The ssh password to connect to the guest" + type = string + default = "Stid_2026-03" +} + +variable "ssh_timeout" { + description = "The timeout waiting for ssh connection" + type = string + default = "30m" +} + +variable "winrm_username" { + description = "The winrm username to connect to the guest. Keep 'Administrator' for Windows Server." + type = string + default = "Installer" +} + +variable "winrm_password" { + description = "The winrm password to connect to the guest." + type = string + default = "Stid_2026-03" +} + +variable "winrm_insecure" { + description = "Skip validating the winrm ssl certificate." + type = bool + default = true +} + +variable "winrm_use_ssl" { + description = "Use winrm ssl connection." + type = bool + default = false +} + +variable "windows_edition" { + description = "Windows edition of the ISO file to install (this is usefull to overwrite for Windows 11 Pro or Server Core/Datacenter)." + type = string + default = "" +} + +variable "windows_language" { + description = "Windows language to use. The ISO file must contain this lanugage." + type = string + default = "en-US" +} + +variable "windows_input_language" { + description = "Windows language for the keyboard to use. The ISO file must contain this lanugage." + type = string + default = "en-US" +} + +variable "provisioner" { + description = "The packer provisioner commands." + type = list(string) +} + +variable "packer_http_interface" { + description = "Name of the network interface that Packer gets HTTPIP from. Defaults to the first non loopback interface." + type = string + default = "" +} + +variable "packer_http_bind_address" { + description = "This is the bind address for the HTTP server. Defaults to 0.0.0.0 so that it will work with any network interface." + type = string + default = "" +} + +variable "packer_http_port" { + description = "Port the HTTP server started to serve the http_directory (required only for ssh portworarding)." + type = number + default = -1 +} diff --git a/template/windows-11.pkrvars.hcl b/template/windows-11.pkrvars.hcl new file mode 100644 index 0000000..9193112 --- /dev/null +++ b/template/windows-11.pkrvars.hcl @@ -0,0 +1,33 @@ + +name = "windows-11-template-nov" +# iso_file = "6e73a606d5a48a7bbac190ab191c4cf5adbfc3a2.iso" +iso_file = "Win11_25H2_French_x64_v2.iso" +iso_url = "https://software-static.download.prss.microsoft.com/dbazure/888969d5-f34g-4e03-ac9d-1f9786c66749/26200.6584.250915-1905.25h2_ge_release_svc_refresh_CLIENTENTERPRISEEVAL_OEMRET_x64FRE_en-us.iso" +iso_checksum = "a61adeab895ef5a4db436e0a7011c92a2ff17bb0357f58b13bbc4062e535e7b9" +disk_size = "64G" +additional_iso_files = [ + { + iso_file = "local:iso/virtio-win.iso" + iso_url = "https://fedorapeople.org/groups/virt/virtio-win/direct-downloads/archive-virtio/virtio-win-0.1.285-1/virtio-win.iso" + iso_checksum = "e14cf2b94492c3e925f0070ba7fdfedeb2048c91eea9c5a5afb30232a3976331" + } +] + +additional_cd_files = [ + { + type = "sata" + index = 3 + files = ["./http/windows-scripts/*"] + } +] +os = "win11" +communicator = "winrm" +http_directory = "" +cloud_init = false +boot_command = [] +provisioner = [] + + + +windows_language="en-US" +windows_input_language="en-US"