#!/usr/bin/env bash # Usage: install.sh server|agent set -euo pipefail set +o xtrace 2>/dev/null || true VAULT_PATH="${K3S_VAULT_PATH:-secret/k3s}" VAULT_FIELD="${K3S_VAULT_FIELD:-server-token}" INSTALL_K3S_VERSION="${INSTALL_K3S_VERSION:-v1.36.2+k3s1}" REMOTE_CONFIG=/etc/rancher/k3s/config.yaml die() { echo "error: $*" >&2; exit 1; } usage() { cat >&2 <<'EOF' Usage: install.sh server|agent EOF exit 2 } scrub() { token='' unset token 2>/dev/null || true } trap scrub EXIT [[ $# -eq 2 ]] || usage role=$1 target=$2 case "$role" in server|agent) ;; *) die "role must be server or agent (got: $role)" ;; esac [[ -n "$target" ]] || die "ssh-target is empty" script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) case "$role" in server) config=$script_dir/config.server.yaml ;; agent) config=$script_dir/config.agent-nas.yaml ;; esac [[ -f "$config" ]] || die "missing config: $config" if grep -qE '^[[:space:]]*token:[[:space:]]' "$config"; then die "config must not contain token: ($config)" fi command -v vault >/dev/null || die "vault CLI not found" command -v ssh >/dev/null || die "ssh not found" command -v scp >/dev/null || die "scp not found" token=$(vault kv get -field="$VAULT_FIELD" "$VAULT_PATH") \ || die "failed to read $VAULT_FIELD from $VAULT_PATH" [[ -n "$token" ]] || die "empty token from $VAULT_PATH field $VAULT_FIELD" echo "role=$role target=$target config=$config version=$INSTALL_K3S_VERSION" ssh -o BatchMode=yes "$target" "install -d -m 0755 /etc/rancher/k3s" scp -o BatchMode=yes -q "$config" "${target}:/tmp/k3s-config.yaml" ssh -o BatchMode=yes "$target" "install -m 0600 /tmp/k3s-config.yaml $REMOTE_CONFIG && rm -f /tmp/k3s-config.yaml" # K3S_TOKEN must not appear in ssh/remote argv (visible in ps). ssh -o BatchMode=yes "$target" 'bash -s' </dev/null || true export INSTALL_K3S_VERSION=$(printf '%q' "$INSTALL_K3S_VERSION") export K3S_TOKEN=$(printf '%q' "$token") curl -sfL https://get.k3s.io | sh -s - $(printf '%q' "$role") unset K3S_TOKEN EOF scrub echo "install finished on $target ($role)"