diff --git a/.mise/lib.sh b/.mise/lib.sh new file mode 100644 index 0000000..311093c --- /dev/null +++ b/.mise/lib.sh @@ -0,0 +1,116 @@ +# shellcheck shell=bash +# Fonctions partagées par les tâches mise (sourcé, non exécutable). + +PROFILES_DIR="${MISE_PROJECT_ROOT:-.}/profiles" + +# shellcheck disable=SC2034 # couleurs utilisées par les tâches +if [ -t 1 ]; then + B=$'\033[1m'; D=$'\033[2m'; R=$'\033[0m' + RED=$'\033[31m'; GREEN=$'\033[32m'; YELLOW=$'\033[33m'; CYAN=$'\033[36m' +else + B=""; D=""; R=""; RED=""; GREEN=""; YELLOW=""; CYAN="" +fi + +die() { echo "${RED}✖${R} $*" >&2; exit 1; } +warn() { echo "${YELLOW}⚠${R} $*" >&2; } +info() { echo "${CYAN}▸${R} $*"; } + +# Forme canonique d'un profil, pour comparer dépôt et LXD : +# - seules name/description/config/devices sont conservées (used_by, project... écartés) +# - les valeurs sont converties en chaînes (LXD stocke `cpu: 1` sous la forme "1") +# - les clés sont triées +# Les clés inconnues (ex. `limits:` imbriqué au lieu de `limits.cpu`) sont gardées +# côté dépôt pour apparaître dans le diff : LXD les ignorerait silencieusement. +YQ_NORMALIZE=' + . as $p + | { + "name": ($p.name // ""), + "description": ($p.description // ""), + "config": (($p.config // {}) | map_values(tostring)), + "devices": (($p.devices // {}) | map_values(map_values(tostring))) + } + + ($p | del(.name, .description, .config, .devices, .used_by, .project)) + | sort_keys(..) + | (.. | select(tag == "!!str")) style = "" + | (.. | select(tag == "!!str" and test("\n"))) style = "literal" +' + +# Liste "nomfichier" des profils du dépôt, triée par nom. +repo_index() { + local f name + while IFS= read -r -d '' f; do + name=$(yq -r '.name // ""' "$f") + printf '%s\t%s\n' "$name" "${f#"${MISE_PROJECT_ROOT:-.}"/}" + done < <(find "$PROFILES_DIR" -type f -name '*.profile.yaml' -print0) | sort +} + +# Résout un argument (chemin de fichier ou nom de profil) en chemin de fichier. +resolve_file() { + local arg="$1" matches + if [ -f "$arg" ]; then + echo "$arg" + return + fi + matches=$(repo_index | awk -F'\t' -v n="$arg" '$1 == n { print $2 }') + case "$(printf '%s' "$matches" | grep -c '^')" in + 0) die "Profil '$arg' introuvable dans le dépôt (ni fichier, ni nom)" ;; + 1) echo "$matches" ;; + *) die "Plusieurs fichiers déclarent le profil '$arg' :"$'\n'"$matches" ;; + esac +} + +profile_name() { yq -r '.name // ""' "$1"; } + +is_installed() { lxc profile show "$1" >/dev/null 2>&1; } + +normalize_file() { yq "$YQ_NORMALIZE" "$1"; } +normalize_installed() { lxc profile show "$1" | yq "$YQ_NORMALIZE"; } + +# Clés de premier niveau du fichier que LXD ne prendrait pas en compte +# (used_by et project, en lecture seule, sont tolérés : fichiers importés). +unknown_keys() { + yq -r 'keys - ["name", "description", "config", "devices", "used_by", "project"] | join(", ")' "$1" +} + +# 0 si le profil installé est identique au fichier du dépôt. +is_same() { + local file="$1" name="$2" + cmp -s <(normalize_file "$file") <(normalize_installed "$name") +} + +# Diff unifié : LXD (installé) → dépôt (ce que `install` appliquerait). +# Rendu avec delta dans un terminal. Retourne 1 s'il y a des différences. +show_diff() { + local file="$1" name="$2" out + out=$(diff -u --label "lxd:$name (installé)" --label "$file (dépôt)" \ + <(normalize_installed "$name") <(normalize_file "$file")) && return 0 + if [ -t 1 ] && command -v delta >/dev/null 2>&1; then + delta --paging=never <<<"$out" + else + printf '%s\n' "$out" + fi + return 1 +} + +has_tty() { [ -t 1 ] && { : /dev/null; } + +# Sélection interactive (gum filter) parmi des lignes lues sur stdin. +pick() { + has_tty && command -v gum >/dev/null 2>&1 || die "Sélection interactive impossible (pas de terminal ou gum absent) : préciser le profil" + gum filter --header "$1" "${@:2}" /dev/null 2>&1; then + gum confirm --default=false --affirmative "Oui" --negative "Non" "$1" /dev/tty + else + read -r -p "$1 [o/N] " answer "$file" + +echo "${GREEN}✔${R} ${B}$name${R} → $file" +if git -C "$MISE_PROJECT_ROOT" ls-files --error-unmatch "$file" >/dev/null 2>&1; then + git -C "$MISE_PROJECT_ROOT" --no-pager diff --stat -- "$file" + echo " ${D}git diff -- $file pour le détail${R}" +else + echo " ${D}nouveau fichier (non suivi par git)${R}" +fi diff --git a/.mise/tasks/install b/.mise/tasks/install new file mode 100755 index 0000000..d2fb075 --- /dev/null +++ b/.mise/tasks/install @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +#MISE description="Installe ou met à jour des profils du dépôt dans LXD" +#MISE quiet=true +#MISE raw=true +#USAGE arg "[profile]..." help="Nom de profil ou fichier du dépôt (défaut : sélection interactive)" +#USAGE flag "-a --all" help="Installe / met à jour tous les profils du dépôt" +#USAGE flag "-y --yes" help="Met à jour sans demander de confirmation" +#USAGE complete "profile" run="mise run --quiet _names" +set -uo pipefail +source "$MISE_PROJECT_ROOT/.mise/lib.sh" + +eval "args=(${usage_profile:-})" +if [ "${#args[@]}" -eq 0 ]; then + if [ "${usage_all:-false}" = "true" ]; then + mapfile -t args < <(repo_index | cut -f2) + else + selection=$(repo_index | cut -f2 | pick "Profils à installer (tab : sélection multiple)" --no-limit) || exit 1 + [ -n "$selection" ] || exit 0 + mapfile -t args <<<"$selection" + fi +fi + +failed=0 +for arg in "${args[@]}"; do + file=$(resolve_file "$arg") || { failed=$((failed + 1)); continue; } + name=$(profile_name "$file") + [ -n "$name" ] || { warn "$file : pas de champ 'name', ignoré"; failed=$((failed + 1)); continue; } + + keys=$(unknown_keys "$file") + if [ -n "$keys" ]; then + warn "$file : clé(s) inconnue(s) de LXD ($keys), profil ignoré" + failed=$((failed + 1)) + continue + fi + + if is_installed "$name"; then + if is_same "$file" "$name"; then + info "${B}$name${R} : déjà à jour" + continue + fi + echo "${YELLOW}⚠${R} ${B}$name${R} existe déjà et diffère du dépôt :" + show_diff "$file" "$name" + if [ "${usage_yes:-false}" != "true" ] && ! confirm "Mettre à jour le profil $name ?"; then + info "$name : inchangé" + continue + fi + else + info "${B}$name${R} : création" + lxc profile create "$name" /dev/null) || die "Impossible d'interroger LXD (lxc profile list)" + +declare -A used +while IFS=, read -r n u; do used[$n]=$u; done <<<"$installed" + +declare -A seen +same=0; changed=0; absent=0 +printf " ${B}%-2s %-26s %-8s %s${R}\n" "" "PROFIL" "UTILISÉ" "FICHIER" +while IFS=$'\t' read -r name file; do + extra="" + if [ -n "${seen[$name]:-}" ]; then + extra=" ${RED}(nom en double : ${seen[$name]})${R}" + fi + seen[$name]=$file + if [ -z "${used[$name]+x}" ]; then + printf " %-2s ${D}%-26s %-8s %s${R}%s\n" "⬜" "$name" "-" "$file" "$extra" + absent=$((absent + 1)) + elif is_same "$file" "$name"; then + printf " %-2s ${GREEN}%-26s${R} %-8s %s%s\n" "✅" "$name" "${used[$name]}" "$file" "$extra" + same=$((same + 1)) + else + printf " %-2s ${YELLOW}%-26s${R} %-8s %s%s\n" "⚠️" "$name" "${used[$name]}" "$file" "$extra" + changed=$((changed + 1)) + fi +done < <(repo_index) + +others=() +for n in "${!used[@]}"; do [ -n "${seen[$n]:-}" ] || others+=("$n"); done +if [ "${usage_all:-false}" = "true" ] && [ "${#others[@]}" -gt 0 ]; then + printf "\n ${B}Hors dépôt${R} ${D}(mise run import )${R}\n" + while IFS= read -r n; do + printf " %-2s ${CYAN}%-26s${R} %-8s\n" "🔹" "$n" "${used[$n]}" + done < <(printf '%s\n' "${others[@]}" | sort) +fi + +echo +echo " ✅ ${same} à jour ⚠️ ${changed} différent(s) ${D}(mise run diff)${R} ⬜ ${absent} non installé(s) 🔹 ${#others[@]} hors dépôt${D}$([ "${usage_all:-false}" = "true" ] || echo ' (--all)')${R}" diff --git a/README.md b/README.md index b0e1293..4080f0a 100644 --- a/README.md +++ b/README.md @@ -7,28 +7,34 @@ This repository contains a collection of LXD profiles and network configurations - `profiles/`: Contains various LXD profile definitions categorized by their purpose (e.g., applications, networking, storage). - `network/`: Defines LXD network configurations. - `docs/`: Additional documentation and helper scripts. -- `install.bash`: A utility script to manage LXD profiles. +- `mise.toml`, `.mise/`: [mise](https://mise.jdx.dev) tasks to manage LXD profiles. ## Usage -### `install.bash` +Prerequisites: [mise](https://mise.jdx.dev) and the `lxc` client. mise installs the +other tools declared in `mise.toml` (`yq`, `gum`, `delta`) with `mise install`. -This script allows you to create and update LXD profiles based on the YAML files in the `profiles/` directory. +A short help message is displayed when entering the directory (mise `enter` hook), +and `mise tasks` lists all available tasks. -#### Update all profiles +A profile can be designated by its name (`docker`) or its file +(`profiles/containerization/docker.profile.yaml`). -To update all profiles defined in this repository, run the script without any arguments: +| Task | Description | +|---|---| +| `mise run list [--all]` | Repository profiles and their state in LXD: ✅ up to date, ⚠️ installed but different, ⬜ not installed. `--all` also shows 🔹 profiles installed in LXD but missing from the repository | +| `mise run diff [profile...]` | Diff between the installed profile (LXD) and the repository file. Without argument, every installed profile that differs. `--exit-code` returns 1 when there are differences | +| `mise run install [profile...]` | Creates or updates profiles. An existing profile that differs shows its diff and asks for confirmation (`--yes` to skip). Without argument, interactive selection; `--all` for every profile | +| `mise run import [profile] [file]` | Writes an installed LXD profile to the repository (without `used_by`, `project`, empty `config`/`devices`). Defaults to the repository file declaring that name, or `profiles/.profile.yaml`. Review with `git diff` before committing | + +Differences are computed on a normalized form (keys sorted, values as strings, +read-only fields dropped), so formatting or quoting alone never shows up as a +change. Top-level keys unknown to LXD (silently ignored by `lxc profile edit`) +are reported, and `install` refuses such files. ```bash -./install.bash +mise run list --all +mise run diff docker +mise run install docker profiles/applications/traefik.profile.yaml +mise run import s3 profiles/applications/s3.profile.yaml && git diff ``` - -#### Update specific profiles - -To update one or more specific profiles, provide their file paths as arguments to the script: - -```bash -./install.bash profiles/containerization/docker.profile.yaml profiles/applications/traefik.profile.yaml -``` - -This will update only the `docker` and `traefik` profiles. diff --git a/docs/create-docker-container.md b/docs/create-docker-container.md index 9ca845b..d202171 100644 --- a/docs/create-docker-container.md +++ b/docs/create-docker-container.md @@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch Or use the local profile: ```bash -./install.bash profiles/containerization/docker.profile.yaml +mise run install profiles/containerization/docker.profile.yaml ``` ## Launch Container diff --git a/docs/create-lxd-manager-container.md b/docs/create-lxd-manager-container.md index 4bd1243..3ad6104 100644 --- a/docs/create-lxd-manager-container.md +++ b/docs/create-lxd-manager-container.md @@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch Or use the local profile: ```bash -./install.bash profiles/containerization/lxd-host-socket.profile.yaml +mise run install profiles/containerization/lxd-host-socket.profile.yaml ``` ## Launch Container diff --git a/docs/create-microk8s-container.md b/docs/create-microk8s-container.md index af8061e..bac2e9e 100644 --- a/docs/create-microk8s-container.md +++ b/docs/create-microk8s-container.md @@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch Or use the local profile: ```bash -./install.bash profiles/containerization/microk8s.profile.yaml +mise run install profiles/containerization/microk8s.profile.yaml ``` ## Launch Container diff --git a/docs/create-traefik-container.md b/docs/create-traefik-container.md index af6d293..a3400b2 100644 --- a/docs/create-traefik-container.md +++ b/docs/create-traefik-container.md @@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch Or use the local profile: ```bash -./install.bash profiles/applications/traefik.profile.yaml +mise run install profiles/applications/traefik.profile.yaml ``` ## Launch Container diff --git a/examples/scripts/create-docker.bash b/examples/scripts/create-docker.bash index 2777324..75292ca 100755 --- a/examples/scripts/create-docker.bash +++ b/examples/scripts/create-docker.bash @@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-docker-container}" echo "Creating Docker container: $CONTAINER_NAME" # Install the profile using the helper script -./install.bash profiles/containerization/docker.profile.yaml +mise run install profiles/containerization/docker.profile.yaml # Launch the container lxc launch ubuntu:lts -p default -p docker "$CONTAINER_NAME" diff --git a/examples/scripts/create-lxd-manager.bash b/examples/scripts/create-lxd-manager.bash index a0ef388..67e30b9 100755 --- a/examples/scripts/create-lxd-manager.bash +++ b/examples/scripts/create-lxd-manager.bash @@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-lxd-manager}" echo "Creating LXD manager container: $CONTAINER_NAME" # Install the profile using the helper script -./install.bash profiles/containerization/lxd-host-socket.profile.yaml +mise run install profiles/containerization/lxd-host-socket.profile.yaml # Launch the container lxc launch ubuntu:lts -p default -p lxd-host-socket "$CONTAINER_NAME" diff --git a/examples/scripts/create-microk8s.bash b/examples/scripts/create-microk8s.bash index 875849c..e147439 100755 --- a/examples/scripts/create-microk8s.bash +++ b/examples/scripts/create-microk8s.bash @@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-microk8s-container}" echo "Creating microk8s container: $CONTAINER_NAME" # Install the profile using the helper script -./install.bash profiles/containerization/microk8s.profile.yaml +mise run install profiles/containerization/microk8s.profile.yaml # Launch the container lxc launch ubuntu:lts -p default -p microk8s "$CONTAINER_NAME" diff --git a/examples/scripts/create-traefik.bash b/examples/scripts/create-traefik.bash index 8c6145c..4b144bb 100755 --- a/examples/scripts/create-traefik.bash +++ b/examples/scripts/create-traefik.bash @@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-traefik-container}" echo "Creating Traefik container: $CONTAINER_NAME" # Install the profile using the helper script -./install.bash profiles/applications/traefik.profile.yaml +mise run install profiles/applications/traefik.profile.yaml # Launch the container lxc launch ubuntu:lts -p default -p traefik "$CONTAINER_NAME" diff --git a/install.bash b/install.bash deleted file mode 100755 index c39635b..0000000 --- a/install.bash +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/bash - -BASEDIR=$(cd "$(dirname "$0")" && pwd) - -echo "BASEDIR=$BASEDIR" - -check_prerequisites() { - # Prerequisite check for yq - if ! command -v yq &> /dev/null - then - echo "Error: yq is not installed." - echo "Please install yq to use this script. Refer to https://github.com/mikefarah/yq#install for installation methods." - exit 1 - fi -} - -update_profile() { - local profile_file="$1" - local profile_name - profile_name=$(yq --expression '.name' "$profile_file") - - if [ -z "$profile_name" ]; then - echo "Error: Could not extract profile name from $profile_file. Skipping." - return 1 - fi - - echo "--- Profile ${profile_name} (from ${profile_file}) ---" - if lxc profile show "${profile_name}" &> /dev/null; then - echo "Profile ${profile_name} already exists. Skipping creation." - else - echo "Profile ${profile_name} does not exist. Creating..." - lxc profile create "${profile_name}" - fi - echo "Updating profile..." - lxc profile edit "${profile_name}" < "${profile_file}" -} - -cd "$BASEDIR" || exit - -check_prerequisites - -if [ "$#" -eq 0 ]; then - # No arguments, update all profiles - echo "No profile specified, updating all profiles..." - find profiles -type f -name "*.profile.yaml" -print0 | while IFS= read -r -d '' file; do - update_profile "$file" - done -else - # Arguments provided, treat them as file paths - for file_path in "$@"; do - if [ -f "$file_path" ]; then - update_profile "$file_path" - else - echo "Error: Profile file '$file_path' not found. Skipping." - fi - done -fi \ No newline at end of file diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..741c66e --- /dev/null +++ b/mise.toml @@ -0,0 +1,35 @@ +[settings] +# Nécessaire pour les hooks (enter) +experimental = true + +[hooks] +enter = "mise run --quiet welcome" + +# Les autres tâches (list, diff, install, import) sont dans .mise/tasks/ +[tasks.welcome] +description = "Affiche un message d'usage basique" +quiet = true +run = ''' +b=$(printf '\033[1m'); d=$(printf '\033[2m'); c=$(printf '\033[36m'); r=$(printf '\033[0m') +cat <