prole/etc/set-k3s-token-1password.sh

57 lines
1.5 KiB
Bash

#!/usr/bin/env bash
# set-k3s-token-1password.sh
# Reads the k3s server join token and stores it in the 'knoey' 1Password vault.
# Replaces etc/set-k3s-token-vault.sh (formerly used ansible-vault).
#
# Run on the k3s control-plane node (requires sudo to read the token file).
set -euo pipefail
TOKEN_FILE="${TOKEN_FILE:-/var/lib/rancher/k3s/server/node-token}"
VAULT="knoey"
ITEM="k3s-token"
FIELD="credential"
if [[ ! -r "$TOKEN_FILE" ]]; then
if command -v sudo >/dev/null 2>&1; then
TOKEN="$(sudo cat "$TOKEN_FILE" | tr -d '\r\n')"
else
echo "ERROR: Cannot read token file: $TOKEN_FILE" >&2
echo "Are you running this on a k3s server?" >&2
exit 1
fi
else
TOKEN="$(cat "$TOKEN_FILE" | tr -d '\r\n')"
fi
if [[ -z "$TOKEN" ]]; then
echo "ERROR: Token read from $TOKEN_FILE is empty" >&2
exit 1
fi
if ! command -v op >/dev/null 2>&1; then
echo "ERROR: 1Password CLI (op) not found. Install: brew install 1password-cli" >&2
exit 1
fi
if ! op whoami >/dev/null 2>&1; then
op signin
fi
if op item get "$ITEM" --vault "$VAULT" >/dev/null 2>&1; then
echo "Updating existing item '$ITEM' in vault '$VAULT'..."
op item edit "$ITEM" --vault "$VAULT" "${FIELD}=${TOKEN}"
else
echo "Creating item '$ITEM' in vault '$VAULT'..."
op item create \
--category login \
--title "$ITEM" \
--vault "$VAULT" \
"${FIELD}=${TOKEN}"
fi
echo "Done. k3s token stored in 1Password vault '$VAULT' as item '$ITEM'."
echo
echo "Verify with:"
echo " op item get $ITEM --vault $VAULT --fields $FIELD --reveal"