fix(infra): guard SSH config write, add ROTATE_KEYS for key rotation

setup_server.sh is now fully idempotent on re-runs:
- deploy key generation was already guarded; SSH config write was not
- SSH config now only written if it doesn't exist (content never changes)
- ROTATE_KEYS=1 deletes the old keypair before generation, prints new
  public key to add to GitLab

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Deeman
2026-02-27 07:12:09 +01:00
parent c778903264
commit d14b45f7d6

View File

@@ -4,6 +4,7 @@
#
# Usage:
# bash infra/setup_server.sh
# ROTATE_KEYS=1 bash infra/setup_server.sh # regenerate SSH deploy key
#
# What it does:
# 1. Creates beanflows_service user (nologin) + adds to docker group
@@ -22,6 +23,8 @@ SSH_DIR="/home/${SERVICE_USER}/.ssh"
DEPLOY_KEY="${SSH_DIR}/materia_deploy"
SOPS_AGE_DIR="/home/${SERVICE_USER}/.config/sops/age"
ROTATE_KEYS="${ROTATE_KEYS:-}"
[ "$(id -u)" = "0" ] || { echo "ERROR: Run as root: sudo bash infra/setup_server.sh"; exit 1; }
log() { echo "$(date '+%H:%M:%S') ==> $*"; }
@@ -53,18 +56,25 @@ log "Setting up SSH deploy key..."
sudo -u "${SERVICE_USER}" mkdir -p "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
if [ -n "${ROTATE_KEYS}" ] && [ -f "${DEPLOY_KEY}" ]; then
log "Rotating SSH deploy key (ROTATE_KEYS set)..."
rm -f "${DEPLOY_KEY}" "${DEPLOY_KEY}.pub"
fi
if [ ! -f "${DEPLOY_KEY}" ]; then
sudo -u "${SERVICE_USER}" ssh-keygen -t ed25519 \
-f "${DEPLOY_KEY}" -N "" -C "materia-deploy"
fi
cat > "${SSH_DIR}/config" <<EOF
if [ ! -f "${SSH_DIR}/config" ]; then
cat > "${SSH_DIR}/config" <<EOF
Host gitlab.com
IdentityFile ${DEPLOY_KEY}
IdentitiesOnly yes
EOF
chown "${SERVICE_USER}:${SERVICE_USER}" "${SSH_DIR}/config"
chmod 600 "${SSH_DIR}/config"
chown "${SERVICE_USER}:${SERVICE_USER}" "${SSH_DIR}/config"
chmod 600 "${SSH_DIR}/config"
fi
ssh-keyscan -H gitlab.com >> "${SSH_DIR}/known_hosts" 2>/dev/null
sort -u "${SSH_DIR}/known_hosts" -o "${SSH_DIR}/known_hosts"