From 146a2494687d416b00fb8acbee20742d6445fc6a Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Fri, 30 Oct 2026 23:13:05 -0600 Subject: [PATCH] Retry transient Kubernetes errors during plans --- lib/jeannie/pipeline.sh | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 3862407..bc0bc10 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -1071,7 +1071,39 @@ run_tofu_plan_stack() { adopt_platform_existing_resources untaint_existing_helm_release "${stack}" 'helm_release.metrics_server["enabled"]' fi - tofu -chdir="${REPO_ROOT}/${stack}" plan "${plan_args[@]}" + tofu_plan_with_kubernetes_retry "${stack}" "${plan_args[@]}" +} + +tofu_plan_with_kubernetes_retry() { + local stack="$1" + shift + local max_attempts="${LAB_TOFU_K8S_PLAN_RETRIES:-3}" + local attempt=1 status output_file + local retry_error_pattern='tls: bad record MAC|TLS handshake timeout|unexpected EOF|unexpected error when reading response body|connection reset by peer|context deadline exceeded|i/o timeout|connection refused|server is currently unable|failed to query with labels' + + if ! [[ "${max_attempts}" =~ ^[1-9][0-9]*$ ]]; then + echo "LAB_TOFU_K8S_PLAN_RETRIES must be a positive integer." >&2 + return 2 + fi + while ((attempt <= max_attempts)); do + output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-plan.XXXXXX")" || return 1 + if tofu -chdir="${REPO_ROOT}/${stack}" plan "$@" >"${output_file}" 2>&1; then + cat "${output_file}" + rm -f "${output_file}" + return 0 + else + status=$? + fi + cat "${output_file}" + if ((attempt >= max_attempts)) || ! grep -Eiq "${retry_error_pattern}" "${output_file}"; then + rm -f "${output_file}" + return "${status}" + fi + rm -f "${output_file}" + attempt=$((attempt + 1)) + echo "OpenTofu ${stack} plan hit a Kubernetes transport error; retrying (${attempt}/${max_attempts}) in 5s..." >&2 + sleep 5 + done } dex_public_url() {