#!/usr/bin/env bash # /usr/local/bin/docker-deploy.sh # # Docker-Compose-Wrapper für Funktions-User (gedacht für Aufruf per sudo). set -Eeuo pipefail IFS=$'\n\t' export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" SCRIPT_NAME="$(basename "$0")" readonly SCRIPT_NAME readonly DEPLOY_SUBDIR="deployment" readonly CONFIG_FILE="/etc/docker-deploy.conf" readonly ALLOWED_ACTIONS=(build up down restart logs pull deploy) # ── Konfiguration ──────────────────────────────────────────────────────────── # Optional: /etc/docker-deploy.conf (root-owned, nicht group/world-writable) mit # DEPLOY_SERVER=H1 # Berechtigte Gruppe: server_${DEPLOY_SERVER}_docker_compose. # Bewusst keine Umgebungsvariable/kein Parameter: sudo-Aufrufer sollen die # Berechtigungsprüfung nicht selbst umstellen können. DEPLOY_SERVER="H1" if [[ -e "$CONFIG_FILE" ]]; then IFS=' ' read -r cfg_owner cfg_mode < <(stat -c '%u %a' "$CONFIG_FILE") if [[ "$cfg_owner" != 0 ]] || (( 8#$cfg_mode & 8#022 )); then echo "❌ $CONFIG_FILE muss root gehören und darf nicht group/world-writable sein" >&2 exit 1 fi DEPLOY_SERVER="$(sed -n 's/^DEPLOY_SERVER=//p' "$CONFIG_FILE" | tail -n1 | tr -d "\"' ")" fi [[ "$DEPLOY_SERVER" =~ ^[A-Za-z0-9_-]+$ ]] || { echo "❌ Ungültiger DEPLOY_SERVER: '$DEPLOY_SERVER'" >&2; exit 1; } readonly DEPLOY_GROUP="server_${DEPLOY_SERVER}_docker_compose" # ── Hilfsfunktionen ────────────────────────────────────────────────────────── log() { printf '[%(%Y-%m-%d %H:%M:%S)T] %s\n' -1 "$*"; } die() { printf '❌ %s\n' "$*" >&2; exit 1; } usage() { cat >&2 < [--cache] Aktionen: ${ALLOWED_ACTIONS[*]} Optionen: --cache Build mit Layer-Cache (Standard bei build/deploy: --no-cache) Beispiel: sudo ${SCRIPT_NAME} func_123 deploy EOF exit 1 } in_array() { local needle="$1"; shift local item for item in "$@"; do [[ "$item" == "$needle" ]] && return 0; done return 1 } user_in_group() { local -a groups IFS=' ' read -ra groups <<<"$(id -nG "$1")" in_array "$2" "${groups[@]}" } on_error() { local rc=$? line=$1 log "💥 Fehlgeschlagen (Exit $rc, Zeile $line): ${APP_USER:-?} ${ACTION:-?}" >&2 exit "$rc" } trap 'on_error $LINENO' ERR # ── Argumente ──────────────────────────────────────────────────────────────── [[ $# -ge 2 && $# -le 3 ]] || usage APP_USER="$1" ACTION="$2" NO_CACHE=(--no-cache) USE_CACHE=false if [[ "${3:-}" == "--cache" ]]; then NO_CACHE=() USE_CACHE=true elif [[ -n "${3:-}" ]]; then usage fi # ── Validierung ────────────────────────────────────────────────────────────── [[ $EUID -eq 0 ]] || die "Muss als root laufen (sudo)" [[ "$APP_USER" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || die "Ungültiger Username: '$APP_USER'" id "$APP_USER" &>/dev/null || die "User '$APP_USER' existiert nicht auf diesem System" user_in_group "$APP_USER" "$DEPLOY_GROUP" || die "User '$APP_USER' ist nicht in Gruppe '$DEPLOY_GROUP'" # Per sudo darf jeder nur für sich selbst deployen (sudoers erlaubt die ganze Gruppe) if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != "root" && "$SUDO_USER" != "$APP_USER" ]]; then die "'$SUDO_USER' darf nicht für '$APP_USER' deployen" fi in_array "$ACTION" "${ALLOWED_ACTIONS[@]}" || die "Unbekannte Aktion: '$ACTION' (erlaubt: ${ALLOWED_ACTIONS[*]})" if $USE_CACHE && [[ "$ACTION" != "build" && "$ACTION" != "deploy" ]]; then die "--cache ist nur bei build/deploy sinnvoll" fi command -v docker >/dev/null || die "docker nicht gefunden" docker compose version &>/dev/null || die "Docker-Compose-Plugin nicht verfügbar" # ── Pfade ──────────────────────────────────────────────────────────────────── HOME_DIR="$(getent passwd "$APP_USER" | cut -d: -f6)" [[ -n "$HOME_DIR" ]] || die "Home-Verzeichnis für '$APP_USER' nicht ermittelbar" # Symlink-Tricks verhindern: aufgelöster Pfad muss unter dem Home bleiben APP_DIR="$(realpath -e -- "${HOME_DIR}/${DEPLOY_SUBDIR}" 2>/dev/null)" \ || die "Verzeichnis nicht gefunden: ${HOME_DIR}/${DEPLOY_SUBDIR}" HOME_REAL="$(realpath -e -- "$HOME_DIR")" [[ "$APP_DIR" == "$HOME_REAL"/* ]] || die "Deploy-Verzeichnis liegt außerhalb des Home: $APP_DIR" COMPOSE_FILE="${APP_DIR}/docker-compose.yml" COMPOSE_OVERRIDE="${APP_DIR}/docker-compose.override.yml" [[ -f "$COMPOSE_FILE" ]] || die "docker-compose.yml nicht gefunden: $COMPOSE_FILE" # ── Nebenläufigkeit: pro User nur ein Lauf gleichzeitig ────────────────────── exec 9>"/run/lock/${SCRIPT_NAME}.${APP_USER}.lock" flock -n 9 || die "Für '$APP_USER' läuft bereits ein Deploy" # ── Compose-Setup ──────────────────────────────────────────────────────────── export COMPOSE_PROJECT_NAME="$APP_USER" COMPOSE_ARGS=(-f "$COMPOSE_FILE") if [[ -f "$COMPOSE_OVERRIDE" ]]; then COMPOSE_ARGS+=(-f "$COMPOSE_OVERRIDE") log "📎 Override: $COMPOSE_OVERRIDE" fi compose() { docker compose "${COMPOSE_ARGS[@]}" "$@"; } log "🚀 Aufrufer: ${SUDO_USER:-root} | User: $APP_USER | Projekt: $COMPOSE_PROJECT_NAME | Pfad: $APP_DIR | Aktion: $ACTION" cd "$APP_DIR" # Fehlerhafte Compose-Dateien früh abfangen (nicht bei down/logs) case "$ACTION" in build|up|restart|pull|deploy) compose config --quiet || die "Compose-Konfiguration ungültig" ;; esac # ── Ausführung ─────────────────────────────────────────────────────────────── case "$ACTION" in build) log "📦 Build..." compose build "${NO_CACHE[@]}" ;; up) log "▶️ Container starten..." compose up -d --remove-orphans ;; down) log "⏹️ Container stoppen..." compose down ;; restart) log "🔄 Container neu starten..." compose restart ;; logs) log "📋 Logs (letzte 100 Zeilen)..." compose logs --tail=100 ;; pull) log "⬇️ Images aktualisieren..." compose pull ;; deploy) log "🚢 Deploy: pull → build → up..." compose pull --ignore-buildable compose build --pull "${NO_CACHE[@]}" compose up -d --remove-orphans compose ps ;; esac log "✅ Fertig: $APP_USER $ACTION"