feat: Use mise tasks to ease list/install/update/diff of LXC profiles between LXC and the repo

This commit is contained in:
xavier committed 2026-11-20 23:40:55 +01:00
1 parent d21bb31d95
commit eff9cfc92c
17 files changed
+359 -81

No files matched your search

+116
View File
@@ -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 "nom<TAB>fichier" 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/tty; } 2>/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/tty
}
# Demande une confirmation oui/non (défaut : non).
confirm() {
local answer
if ! has_tty; then
warn "Pas de terminal pour confirmer (utiliser --yes)"
return 1
fi
if command -v gum >/dev/null 2>&1; then
gum confirm --default=false --affirmative "Oui" --negative "Non" "$1" </dev/tty >/dev/tty
else
read -r -p "$1 [o/N] " answer </dev/tty
[[ "$answer" =~ ^[oOyY] ]]
fi
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
#MISE description="(interne) Noms des profils du dépôt, pour l'autocomplétion"
#MISE hide=true
source "$MISE_PROJECT_ROOT/.mise/lib.sh"
repo_index | cut -f1 | uniq
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
#MISE description="Affiche le diff entre un profil du dépôt et le profil installé dans LXD"
#MISE quiet=true
#USAGE arg "[profile]..." help="Nom de profil ou fichier du dépôt (défaut : tous les profils installés)"
#USAGE flag "--exit-code" help="Code retour 1 en cas de différence (comme git diff --exit-code)"
#USAGE complete "profile" run="mise run --quiet _names"
set -uo pipefail
source "$MISE_PROJECT_ROOT/.mise/lib.sh"
eval "args=(${usage_profile:-})"
all=false
if [ "${#args[@]}" -eq 0 ]; then
all=true
mapfile -t args < <(repo_index | cut -f2)
fi
status=0
for arg in "${args[@]}"; do
file=$(resolve_file "$arg") || { status=2; continue; }
name=$(profile_name "$file")
if ! is_installed "$name"; then
$all || warn "$name : non installé dans LXD"
continue
fi
keys=$(unknown_keys "$file")
[ -z "$keys" ] || warn "$file : clé(s) ignorée(s) par LXD : $keys"
if show_diff "$file" "$name"; then
$all || info "$name : identique"
else
status=1
fi
done
[ "$status" -eq 1 ] && [ "${usage_exit_code:-false}" != "true" ] && status=0
exit "$status"
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
#MISE description="Importe un profil installé dans LXD vers un fichier du dépôt"
#MISE quiet=true
#USAGE arg "[profile]" help="Nom du profil LXD (défaut : sélection interactive)"
#USAGE arg "[file]" help="Fichier de destination (défaut : fichier existant du dépôt, sinon profiles/<profil>.profile.yaml)"
#USAGE complete "profile" run="lxc profile list --format csv --columns n"
set -euo pipefail
source "$MISE_PROJECT_ROOT/.mise/lib.sh"
name="${usage_profile:-}"
[ -n "$name" ] || name=$(lxc profile list --format csv --columns n | pick "Profil LXD à importer")
is_installed "$name" || die "Profil '$name' absent de LXD"
file="${usage_file:-}"
if [ -z "$file" ]; then
file=$(repo_index | awk -F'\t' -v n="$name" '$1 == n { print $2; exit }')
file="${file:-profiles/$name.profile.yaml}"
fi
mkdir -p "$(dirname "$file")"
# Champs en lecture seule ou propres à l'installation retirés,
# ainsi que config/devices vides, pour un fichier minimal.
lxc profile show "$name" \
| yq '
del(.used_by, .project)
| del(.config | select(length == 0))
| del(.devices | select(length == 0))
' >"$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
+59
View File
@@ -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 || { failed=$((failed + 1)); continue; }
fi
# used_by/project éventuels (fichiers importés) sont retirés avant l'édition
if yq 'del(.used_by, .project)' "$file" | lxc profile edit "$name"; then
echo "${GREEN}✔${R} ${B}$name${R} : à jour (depuis $file)"
else
failed=$((failed + 1))
fi
done
[ "$failed" -eq 0 ] || die "$failed profil(s) en erreur"
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
#MISE description="Liste les profils du dépôt et leur état dans LXD"
#MISE quiet=true
#USAGE flag "-a --all" help="Affiche aussi les profils installés dans LXD absents du dépôt"
set -euo pipefail
source "$MISE_PROJECT_ROOT/.mise/lib.sh"
installed=$(lxc profile list --format csv --columns n,u 2>/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 <profil>)${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}"
+22 -16
View File
@@ -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). - `profiles/`: Contains various LXD profile definitions categorized by their purpose (e.g., applications, networking, storage).
- `network/`: Defines LXD network configurations. - `network/`: Defines LXD network configurations.
- `docs/`: Additional documentation and helper scripts. - `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 ## 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>.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 ```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.
+1 -1
View File
@@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch
Or use the local profile: Or use the local profile:
```bash ```bash
./install.bash profiles/containerization/docker.profile.yaml mise run install profiles/containerization/docker.profile.yaml
``` ```
## Launch Container ## Launch Container
+1 -1
View File
@@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch
Or use the local profile: Or use the local profile:
```bash ```bash
./install.bash profiles/containerization/lxd-host-socket.profile.yaml mise run install profiles/containerization/lxd-host-socket.profile.yaml
``` ```
## Launch Container ## Launch Container
+1 -1
View File
@@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch
Or use the local profile: Or use the local profile:
```bash ```bash
./install.bash profiles/containerization/microk8s.profile.yaml mise run install profiles/containerization/microk8s.profile.yaml
``` ```
## Launch Container ## Launch Container
+1 -1
View File
@@ -12,7 +12,7 @@ curl https://gitea.cloud.logerais.com/cloud.logerais.com/lxd-profiles/raw/branch
Or use the local profile: Or use the local profile:
```bash ```bash
./install.bash profiles/applications/traefik.profile.yaml mise run install profiles/applications/traefik.profile.yaml
``` ```
## Launch Container ## Launch Container
+1 -1
View File
@@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-docker-container}"
echo "Creating Docker container: $CONTAINER_NAME" echo "Creating Docker container: $CONTAINER_NAME"
# Install the profile using the helper script # 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 # Launch the container
lxc launch ubuntu:lts -p default -p docker "$CONTAINER_NAME" lxc launch ubuntu:lts -p default -p docker "$CONTAINER_NAME"
+1 -1
View File
@@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-lxd-manager}"
echo "Creating LXD manager container: $CONTAINER_NAME" echo "Creating LXD manager container: $CONTAINER_NAME"
# Install the profile using the helper script # 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 # Launch the container
lxc launch ubuntu:lts -p default -p lxd-host-socket "$CONTAINER_NAME" lxc launch ubuntu:lts -p default -p lxd-host-socket "$CONTAINER_NAME"
+1 -1
View File
@@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-microk8s-container}"
echo "Creating microk8s container: $CONTAINER_NAME" echo "Creating microk8s container: $CONTAINER_NAME"
# Install the profile using the helper script # 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 # Launch the container
lxc launch ubuntu:lts -p default -p microk8s "$CONTAINER_NAME" lxc launch ubuntu:lts -p default -p microk8s "$CONTAINER_NAME"
+1 -1
View File
@@ -5,7 +5,7 @@ CONTAINER_NAME="${1:-traefik-container}"
echo "Creating Traefik container: $CONTAINER_NAME" echo "Creating Traefik container: $CONTAINER_NAME"
# Install the profile using the helper script # 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 # Launch the container
lxc launch ubuntu:lts -p default -p traefik "$CONTAINER_NAME" lxc launch ubuntu:lts -p default -p traefik "$CONTAINER_NAME"
-57
View File
@@ -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
+35
View File
@@ -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 <<MSG
${c}╭────────────────────────────────────────────────────────╮${r}
${c}│${r} 📦 ${b}lxd-profiles${r} · profils et réseaux LXD ${c}│${r}
${c}╰────────────────────────────────────────────────────────╯${r}
🗂️ ${b}Profils${r}
▸ mise run list [--all] ${d}profils du dépôt et état dans LXD (✅ ⚠️ ⬜ 🔹)${r}
▸ mise run diff [profil...] ${d}diff installé (LXD) → dépôt${r}
▸ mise run install [profil...] ${d}crée / met à jour (diff + confirmation, --all, --yes)${r}
▸ mise run import [profil] [f] ${d}exporte un profil LXD vers le dépôt (puis git diff)${r}
${d}profil = nom (ex. docker) ou fichier (ex. profiles/containerization/docker.profile.yaml)${r}
💡 ${d}mise tasks pour lister toutes les tâches${r}
MSG
'''
[tools]
delta = "latest"
gum = "latest"
yq = "latest"