Posted in

OpenShift – Restore SSH access

If you lost your SSH key to your OpenShift cluster, but you still have a cluster-admin access tagged to your user. Use the following script to restore your SSH key automatically.

You can choose to specify your existing key stored in ~/.ssh/, replace SSH_KEY_NAME with your ssh key.

restore_ssh.sh
#!/usr/bin/env bash
set -euo pipefail

SSH_KEY_NAME="${SSH_KEY_NAME:-id_ed25519_ocpnode}"
SSH_USER="${SSH_USER:-core}"

echo "[*] Detecting node..."
NODE_NAME="$(oc get nodes -o jsonpath='{.items[0].metadata.name}')"
if [[ -z "${NODE_NAME}" ]]; then
  echo "[-] Could not detect a node. Are you logged into the cluster? (oc whoami)" >&2
  exit 1
fi
NODE_IP="$(oc get node "${NODE_NAME}" -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}')"
if [[ -z "${NODE_IP}" ]]; then
  echo "[-] Could not get node InternalIP. Check: oc get node ${NODE_NAME} -o yaml" >&2
  exit 1
fi
echo "[+] Node: ${NODE_NAME} (IP: ${NODE_IP})"

# 1) Generate a keypair locally if missing
if [[ ! -f "${HOME}/.ssh/${SSH_KEY_NAME}" ]]; then
  echo "[*] Generating SSH keypair: ${HOME}/.ssh/${SSH_KEY_NAME}"
  ssh-keygen -t ed25519 -f "${HOME}/.ssh/${SSH_KEY_NAME}" -C "ocp-node-access" -N ""
else
  echo "[=] Key already exists: ${HOME}/.ssh/${SSH_KEY_NAME}"
fi

PUBKEY_CONTENT="$(cat "${HOME}/.ssh/${SSH_KEY_NAME}.pub")"

# 2) Inject public key into the node using oc debug + chroot
echo "[*] Injecting public key into ${SSH_USER}@${NODE_NAME} ..."
oc debug "node/${NODE_NAME}" -- chroot /host bash -c "
  set -euo pipefail
  HOME_DIR=\$(getent passwd '${SSH_USER}' | cut -d: -f6 || true)
  if [[ -z \"\${HOME_DIR}\" ]]; then
    echo '[-] User ${SSH_USER} not found on node' >&2
    exit 1
  fi
  mkdir -p \"\${HOME_DIR}/.ssh\"
  touch \"\${HOME_DIR}/.ssh/authorized_keys\"
  chmod 700 \"\${HOME_DIR}/.ssh\"
  chmod 600 \"\${HOME_DIR}/.ssh/authorized_keys\"
  if ! grep -qF '${PUBKEY_CONTENT}' \"\${HOME_DIR}/.ssh/authorized_keys\"; then
    echo '${PUBKEY_CONTENT}' >> \"\${HOME_DIR}/.ssh/authorized_keys\"
  fi
  chown -R '${SSH_USER}:${SSH_USER}' \"\${HOME_DIR}/.ssh\"
"
echo "[+] Key installed."

echo
echo "[*] You can now SSH into the node with:"
echo "ssh -i \"${HOME}/.ssh/${SSH_KEY_NAME}\" ${SSH_USER}@${NODE_IP}"

Leave a Reply

Your email address will not be published. Required fields are marked *