Restore private OCI edge management through Bastion
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-05 12:34:56 -06:00
parent 1c8b8580d7
commit 566af7fe72
4 changed files with 133 additions and 51 deletions

View File

@ -80,13 +80,17 @@ Review imports and additions in the complete plan. A second successful apply
should produce no further imports or infrastructure changes. The offline
regressions use temporary files and mocks; they never contact OCI or SSH.
Edge deployment defaults to `LAB_EDGE_SSH_TRANSPORT=tailscale`. It resolves the
recorded OCI VM and its public address for DNS, then finds the single online
Edge deployment defaults to `LAB_EDGE_SSH_TRANSPORT=auto`. It resolves the
recorded OCI VM and its public address for DNS, then tries the single online
Tailscale peer named `homelab-oci-edge` for SSH. Override the peer name with
`LAB_EDGE_TAILSCALE_HOSTNAME`. `LAB_EDGE_SSH_TRANSPORT=bastion` selects the
existing Bastion workflow explicitly. A missing/offline tailnet peer fails before
provisioning; a first boot without Tailscale needs the Bastion transport.
SSH uses a single bounded authentication check and preserves known host keys.
`LAB_EDGE_TAILSCALE_HOSTNAME`. If the peer is unavailable or its SSH preflight
fails, Jeannie selects an OCI Bastion port-forwarding session to the edge's private IP.
`LAB_EDGE_SSH_TRANSPORT=tailscale` and `bastion` select either path explicitly.
The Bastion path requires a reachable Bastion service, a working SSH server on
the edge, an authorized guest SSH key, and an allowed private subnet. It does
not require the OCI guest agent and never falls back to public SSH. A fresh edge
without Tailscale uses Bastion to bootstrap it before reconciling subnet routes.
Both paths use bounded SSH preflight and preserve known host keys.
Routine applies no longer restart caches; use `./jeannie edge-cache-flush`
when a cache reset is intended.

View File

@ -801,7 +801,9 @@ run_tofu_stack() {
ensure_cluster_worker_var_file
fi
if [[ "${stack}" == "bootstrap/edge" ]]; then
ensure_edge_tailscale_routes || return 1
if [[ "${LAB_EDGE_DEFER_TAILSCALE_ROUTES:-false}" != true ]]; then
ensure_edge_tailscale_routes || return 1
fi
ensure_edge_haproxy_stats_password
fi
if truthy "${auto_approve}"; then
@ -3596,10 +3598,7 @@ check_debian_tailscale_ip() {
}
check_edge_ssh() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" "true"
prepare_edge_connection
}
check_rpi_ssh() {
@ -3699,11 +3698,10 @@ sudo rm -f \"\$root/.homelab-check/write-test\""
}
check_edge_disk_free() {
local edge_host="${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}"
local edge_user="${LAB_EDGE_USER:-ubuntu}"
local min_gib="${LAB_PREFLIGHT_EDGE_MIN_FREE_GIB:-2}"
ssh -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${edge_user}@${edge_host}" "set -eu
[[ "${min_gib}" =~ ^[0-9]+$ ]] || { echo "Invalid edge minimum free space." >&2; return 1; }
prepare_edge_connection || return 1
ssh "${EDGE_SSH_ARGS[@]}" "${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}@${TF_VAR_edge_ssh_host}" "set -eu
available_kib=\"\$(df -Pk / | awk 'NR == 2 { print \$4 }')\"
min_kib=$((min_gib * 1024 * 1024))
if [ \"\$available_kib\" -lt \"\$min_kib\" ]; then
@ -3769,7 +3767,7 @@ homelab_preflight() {
fi
preflight_warn "RPi Tailscale IP ${LAB_RPI_TAILSCALE_IP:-unset}" check_rpi_tailscale_ip
preflight_check "Pimox storage ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}} is active" check_pimox_storage || failures=$((failures + 1))
preflight_check "OCI edge SSH ${LAB_EDGE_USER:-ubuntu}@${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}" check_edge_ssh || failures=$((failures + 1))
preflight_check "OCI edge private management access" check_edge_ssh || failures=$((failures + 1))
if ((failures > 0)); then
echo "Preflight failed with ${failures} blocking check(s). Fix the inventory or host state before continuing." >&2
@ -8237,25 +8235,22 @@ platform_apply() {
remember_cluster_profile || return 1
}
edge_apply() {
require_debian_server "edge"
prepare_edge_connection() {
# The remote API is a long-lived service and does not inherit the shell's
# OCI exports. Load the persisted foundation inputs before endpoint
# discovery so recreated instances are resolved before any SSH connection.
if declare -F oci_foundation_load_config >/dev/null 2>&1; then
oci_foundation_load_config
fi
local requested_transport="${LAB_EDGE_SSH_TRANSPORT:-auto}"
local configured_edge_key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-}}"
if [[ -n "${configured_edge_key}" ]]; then
export TF_VAR_edge_ssh_key_path="${configured_edge_key}"
fi
refresh_oci_edge_endpoint || return 1
if [[ "${LAB_EDGE_SSH_TRANSPORT:-tailscale}" == "bastion" ]]; then
if [[ "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${requested_transport}}" == "bastion" ]]; then
oci_ensure_edge_bastion_ingress || return 1
if [[ -n "${LAB_OCI_EDGE_INSTANCE_ID:-}" ]]; then
oci_enable_bastion_plugin "${LAB_OCI_EDGE_INSTANCE_ID}" || return 1
fi
prepare_oci_edge_bastion || return 1
fi
edge_require_ssh_transport || return 1
@ -8263,9 +8258,58 @@ edge_apply() {
local ssh_host="${TF_VAR_edge_ssh_host}" ssh_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
# One bounded authentication check gives a useful error before OpenTofu
# can retry the same inaccessible host for several minutes.
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true || return 1
if ! ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true; then
if [[ "${requested_transport}" != auto || "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-}" != tailscale ]]; then
return 1
fi
echo "Tailscale SSH preflight failed; trying OCI Bastion private access." >&2
local resolved_bastion
resolved_bastion="$(LAB_EDGE_SSH_TRANSPORT=bastion python3 "${REPO_ROOT}/scripts/oci-foundation-resolve.py" edge --repo "${REPO_ROOT}")" || return 1
eval "${resolved_bastion}"
oci_ensure_edge_bastion_ingress || return 1
prepare_oci_edge_bastion || return 1
edge_require_ssh_transport || return 1
edge_ssh_args
ssh_host="${TF_VAR_edge_ssh_host}"
ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" true || return 1
fi
}
edge_apply() {
require_debian_server "edge"
local LAB_EDGE_DEFER_TAILSCALE_ROUTES=false
export LAB_EDGE_DEFER_TAILSCALE_ROUTES
prepare_edge_connection || return 1
local ssh_host="${TF_VAR_edge_ssh_host}" ssh_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
if ! ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
'command -v tailscale >/dev/null 2>&1 && test -n "$(tailscale ip -4 2>/dev/null)"'; then
echo "Edge Tailscale is not ready; route reconciliation will follow bootstrap."
LAB_EDGE_DEFER_TAILSCALE_ROUTES=true
if ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" 'command -v tailscale >/dev/null 2>&1'; then
local edge_auth_key="${TF_VAR_edge_tailscale_auth_key:-}"
local edge_tag="${TF_VAR_edge_tailscale_tag:-tag:homelab-edge}"
if [[ -z "${edge_auth_key}" ]]; then
echo "Tailscale is installed but not connected. Provide LAB_EDGE_TAILSCALE_AUTH_KEY or the configured OAuth credential file." >&2
return 1
fi
if [[ ! "${edge_tag}" =~ ^tag:[a-zA-Z0-9-]+$ ]]; then
echo "Invalid edge Tailscale tag." >&2
return 1
fi
echo "Reconnecting edge Tailscale through the authenticated private management path..."
if ! printf '%s' "${edge_auth_key}" | ssh "${EDGE_SSH_ARGS[@]}" "${ssh_user}@${ssh_host}" \
"sudo -n sh -c 'set -eu; umask 077; key_file=\$(mktemp /run/jeannie-edge-ts.XXXXXX); trap '\''rm -f \"\$key_file\"'\'' EXIT; cat >\"\$key_file\"; systemctl start tailscaled; tailscale up --auth-key=\"file:\$key_file\" --hostname=homelab-oci-edge --advertise-tags=\"\$1\" --accept-routes' sh '${edge_tag}'"; then
echo "Could not reconnect edge Tailscale; check the private management path and auth key." >&2
return 1
fi
fi
fi
run_tofu_stack "bootstrap/edge" || return 1
if [[ "${LAB_EDGE_DEFER_TAILSCALE_ROUTES}" == true ]]; then
ensure_edge_tailscale_routes || return 1
fi
# OpenTofu does not rerun provisioners when inputs are unchanged. Reconcile
# stopped containers and check the deployed proxy without recreating them.
edge_ssh_args
@ -8300,6 +8344,7 @@ edge_apply() {
refresh_oci_edge_endpoint() {
local resolved
unset LAB_EDGE_RESOLVED_SSH_TRANSPORT
unset TF_VAR_edge_ssh_host TF_VAR_edge_bastion_host TF_VAR_edge_bastion_user
unset TF_VAR_edge_bastion_port TF_VAR_edge_bastion_private_key_path
unset LAB_OCI_EDGE_BASTION_PROXY_COMMAND LAB_OCI_EDGE_BASTION_SESSION_ID
@ -8345,6 +8390,16 @@ oci_ensure_edge_bastion_ingress() {
echo "Cannot ensure Bastion ingress: target subnet CIDR is unavailable." >&2
return 1
fi
if ! python3 -c 'import ipaddress,sys
try:
n=ipaddress.ip_network(sys.argv[1], strict=True)
ranges=[ipaddress.ip_network(x) for x in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
sys.exit(0 if n.version==4 and any(n.subnet_of(r) for r in ranges) else 1)
except ValueError:
sys.exit(1)' "${source_cidr}"; then
echo "Refusing Bastion SSH ingress: source must be a private IPv4 subnet, not ${source_cidr}." >&2
return 1
fi
vnic_id="$("${oci_bin}" compute vnic-attachment list \
--compartment-id "${edge_compartment}" \
--instance-id "${edge_instance}" \
@ -8393,7 +8448,6 @@ prepare_oci_edge_bastion() {
local bastion_id="${LAB_OCI_BASTION_ID:-}"
local target_id="${LAB_OCI_EDGE_INSTANCE_ID:-}"
local target_host="${TF_VAR_edge_ssh_host:-}"
local target_user="${TF_VAR_edge_user:-${LAB_EDGE_USER:-ubuntu}}"
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}}"
local public_key="${edge_key}.pub"
local region="${LAB_OCI_REGION:-}"
@ -8404,7 +8458,7 @@ prepare_oci_edge_bastion() {
local session_id=""
local session_error
local attempt
local session_name="jeannie-edge-${target_id##*.}"
local session_name
local proxy_command
unset TF_VAR_edge_bastion_host TF_VAR_edge_bastion_user TF_VAR_edge_bastion_port
@ -8430,6 +8484,18 @@ prepare_oci_edge_bastion() {
echo "OCI Bastion edge SSH key pair is not readable: ${edge_key}" >&2
return 1
fi
if ! python3 -c 'import ipaddress,sys
try:
a=ipaddress.ip_address(sys.argv[1]); networks=[ipaddress.ip_network(x) for x in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
sys.exit(0 if a.version==4 and any(a in n for n in networks) else 1)
except ValueError:
sys.exit(1)' "${target_host}"; then
echo "Refusing Bastion forwarding to a non-private IPv4 address." >&2
return 1
fi
local key_digest
key_digest="$(sha256sum "${public_key}" | cut -c1-12)" || return 1
session_name="jeannie-pf-${target_id##*.}-${target_host//./-}-${key_digest}"
if ! declare -F oci_cli_resolve >/dev/null 2>&1 || ! oci_bin="$(oci_cli_resolve 2>/dev/null)"; then
echo "OCI CLI is required to create the edge Bastion session." >&2
return 1
@ -8450,11 +8516,11 @@ prepare_oci_edge_bastion() {
break
fi
session_id=""
session_json="$(${oci_bin} bastion session create-managed-ssh \
session_json="$(${oci_bin} bastion session create-port-forwarding \
--bastion-id "${bastion_id}" \
--display-name "${session_name}" \
--target-resource-id "${target_id}" \
--target-os-username "${target_user}" \
--target-private-ip "${target_host}" \
--target-port 22 \
--ssh-public-key-file "${public_key}" \
--session-ttl "${session_ttl}" \
--wait-for-state SUCCEEDED --output json 2>"${session_error}" || true)"
@ -8468,13 +8534,13 @@ prepare_oci_edge_bastion() {
# resulting session appears in the list API.
session_id=""
if (( attempt < 6 )); then
printf 'Waiting for OCI Bastion plugin/session readiness (retry %d/6)...\n' "${attempt}" >&2
printf 'Waiting for OCI Bastion forwarding session readiness (retry %d/6)...\n' "${attempt}" >&2
sleep 10
fi
done
if [[ -z "${session_id}" || "${session_id}" == "null" ||
"${session_id}" != ocid1.bastionsession.* ]]; then
echo "Unable to create an OCI Bastion managed SSH session for the edge instance." >&2
echo "Unable to create an OCI Bastion port-forwarding session for the edge instance." >&2
sed -n '1,80p' "${session_error}" >&2 || true
rm -f "${session_error}"
return 1
@ -8513,7 +8579,7 @@ refresh_oci_edge_host_key() {
}
edge_require_ssh_transport() {
case "${LAB_EDGE_SSH_TRANSPORT:-tailscale}" in
case "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${LAB_EDGE_SSH_TRANSPORT:-tailscale}}" in
tailscale)
if [[ -z "${TF_VAR_edge_ssh_host:-}" ||
"${TF_VAR_edge_ssh_host}" != "${LAB_EDGE_TAILSCALE_IP:-}" ]]; then
@ -8529,7 +8595,7 @@ edge_require_ssh_transport() {
fi
;;
*)
echo "LAB_EDGE_SSH_TRANSPORT must be tailscale or bastion." >&2
echo "Edge SSH transport is unresolved; choose auto, tailscale, or bastion." >&2
return 1
;;
esac
@ -8538,7 +8604,7 @@ edge_require_ssh_transport() {
edge_ssh_args() {
local edge_key="${TF_VAR_edge_ssh_key_path:-${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}}"
EDGE_SSH_ARGS=(-i "${edge_key}" -o BatchMode=yes -o ConnectTimeout="${LAB_EDGE_SSH_PREFLIGHT_SECONDS:-10}" -o ConnectionAttempts=1 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new)
if [[ "${LAB_EDGE_SSH_TRANSPORT:-tailscale}" == "tailscale" ]]; then
if [[ "${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-${LAB_EDGE_SSH_TRANSPORT:-tailscale}}" == "tailscale" ]]; then
# Direct tailnet SSH must also bypass ProxyJump/ProxyCommand inherited
# from an operator's SSH config or a previous Bastion invocation.
EDGE_SSH_ARGS+=( -o ProxyCommand=none -o ProxyJump=none )
@ -8572,9 +8638,7 @@ edge_remote_failure_report() {
edge_diagnose() {
require_debian_server "edge diagnose"
oci_foundation_load_config || return 1
refresh_oci_edge_endpoint || return 1
edge_require_ssh_transport || return 1
prepare_edge_connection || return 1
edge_remote_failure_report
}
@ -8784,7 +8848,7 @@ if ! command -v tailscale >/dev/null 2>&1; then
fi
sudo tailscale set --accept-routes=true
"; then
echo "OCI edge SSH preflight failed via ${LAB_EDGE_SSH_TRANSPORT:-tailscale} (${edge_host})." >&2
echo "OCI edge SSH preflight failed via ${LAB_EDGE_RESOLVED_SSH_TRANSPORT:-unknown} (${edge_host})." >&2
return 1
fi
}
@ -9102,7 +9166,7 @@ up() {
run_step "Version report" doctor_versions_report
run_step "Platform OpenTofu apply" run_tofu_stack "bootstrap/platform"
run_step "Applications" apps
run_step "Edge OpenTofu apply" run_tofu_stack "bootstrap/edge"
run_step "Edge OpenTofu apply" edge_apply
run_step "Debian Kubernetes offload cleanup" cleanup_debian_k8s_after_pimox_offload
echo "Deployment successfully completed."

View File

@ -31,7 +31,7 @@ homelab_preflight() {
fi
preflight_warn "RPi Tailscale IP ${LAB_RPI_TAILSCALE_IP:-unset}" check_rpi_tailscale_ip
preflight_check "Selected cluster storage" status_cluster_storage bootstrap || failures=$((failures + 1))
preflight_check "OCI edge SSH ${LAB_EDGE_USER:-ubuntu}@${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}" check_edge_ssh || failures=$((failures + 1))
preflight_check "OCI edge private management access" check_edge_ssh || failures=$((failures + 1))
if ((failures > 0)); then
echo "Preflight failed with ${failures} blocking check(s). Fix the inventory or host state before continuing." >&2

View File

@ -381,6 +381,10 @@ def resolve_edge():
vm = oci.instance("edge")
if not vm or vm.get("lifecycle-state") != "RUNNING":
raise ValueError("The managed OCI edge is absent or not RUNNING")
state = read_state(state_path(os.environ, Path(__file__).resolve().parents[1]))
recorded_edge = resources(state).get("oci_core_instance.edge", {}).get("id")
if recorded_edge and recorded_edge != vm.get("id"):
raise ValueError("Discovered edge does not match the instance in the selected foundation state")
vnic = oci.vnic(vm)
if not vnic.get("public-ip"):
raise ValueError("The edge VNIC has no public IP for DNS")
@ -389,25 +393,35 @@ def resolve_edge():
"LAB_OCI_EDGE_PRIVATE_IP": vnic["private-ip"],
"LAB_EDGE_HOST": vnic["public-ip"], "TF_VAR_edge_host": vnic["public-ip"],
"TF_VAR_edge_instance_id": vm["id"]}
transport = os.environ.get("LAB_EDGE_SSH_TRANSPORT", "tailscale")
if transport == "tailscale":
transport = os.environ.get("LAB_EDGE_SSH_TRANSPORT", "auto")
if transport in ("auto", "tailscale"):
# Resolve the tailnet peer by identity, never by a stale inventory IP.
command = subprocess.run(["tailscale", "status", "--json"], capture_output=True,
text=True, timeout=15, check=True)
peers = json.loads(command.stdout).get("Peer", {}).values()
try:
command = subprocess.run(["tailscale", "status", "--json"], capture_output=True,
text=True, timeout=15, check=True)
peers = (json.loads(command.stdout).get("Peer") or {}).values()
except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
if transport != "auto":
raise ValueError(f"Cannot inspect Tailscale peers: {error}") from error
peers = []
hostname = os.environ.get("LAB_EDGE_TAILSCALE_HOSTNAME", "homelab-oci-edge")
matches = [x for x in peers if x.get("HostName") == hostname and x.get("Online")
and any(ip.startswith("100.") for ip in x.get("TailscaleIPs", []))]
if len(matches) != 1:
if len(matches) > 1 or (not matches and transport == "tailscale"):
raise ValueError(f"Expected one online Tailscale peer named {hostname}; found {len(matches)}")
peer = matches[0]
ip = next(ip for ip in peer["TailscaleIPs"] if ip.startswith("100."))
print(f"Using Tailscale peer {hostname} ({ip}) for OCI edge {vm['id']}", file=sys.stderr)
values.update(LAB_EDGE_TAILSCALE_IP=ip, TF_VAR_edge_ssh_host=ip)
if matches:
peer = matches[0]
ip = next(ip for ip in peer["TailscaleIPs"] if ip.startswith("100."))
print(f"Using Tailscale peer {hostname} ({ip}) for OCI edge {vm['id']}", file=sys.stderr)
values.update(LAB_EDGE_TAILSCALE_IP=ip, TF_VAR_edge_ssh_host=ip,
LAB_EDGE_RESOLVED_SSH_TRANSPORT="tailscale")
else:
print("Edge Tailscale peer unavailable; selecting OCI Bastion private access.", file=sys.stderr)
values.update(TF_VAR_edge_ssh_host=vnic["private-ip"], LAB_EDGE_RESOLVED_SSH_TRANSPORT="bastion")
elif transport == "bastion":
values["TF_VAR_edge_ssh_host"] = vnic["private-ip"]
values.update(TF_VAR_edge_ssh_host=vnic["private-ip"], LAB_EDGE_RESOLVED_SSH_TRANSPORT="bastion")
else:
raise ValueError("LAB_EDGE_SSH_TRANSPORT must be tailscale or bastion")
raise ValueError("LAB_EDGE_SSH_TRANSPORT must be auto, tailscale or bastion")
emit(values)