fix: retry app apply on API flaps
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-10-05 13:47:06 -06:00
parent b09453843a
commit ec2f107f76
1 changed files with 48 additions and 1 deletions

View File

@ -559,6 +559,53 @@ delete_prometheus_stack_storage() {
fi
}
tofu_apply_with_kubernetes_retry() {
local stack="$1"
shift
local max_attempts="${LAB_TOFU_K8S_APPLY_RETRIES:-3}"
local retry_sleep="${LAB_TOFU_K8S_APPLY_RETRY_SLEEP_SECONDS:-30}"
local attempt=1
local status=0
local output_file
while true; do
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-apply.XXXXXX")"
set +e
tofu -chdir="${REPO_ROOT}/${stack}" apply "$@" 2>&1 | tee "${output_file}"
status="${PIPESTATUS[0]}"
set -e
if ((status == 0)); then
rm -f "${output_file}"
return 0
fi
if [[ "${stack}" != "bootstrap/platform" && "${stack}" != "bootstrap/apps" ]]; then
rm -f "${output_file}"
return "${status}"
fi
if ! grep -Eiq \
'cannot get OpenAPI|failed get OpenAPI spec|context deadline exceeded|TLS handshake timeout|connection refused|unexpected EOF|server is currently unable' \
"${output_file}"; then
rm -f "${output_file}"
return "${status}"
fi
if ((attempt >= max_attempts)); then
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI errors after ${attempt} attempt(s)." >&2
rm -f "${output_file}"
return "${status}"
fi
attempt=$((attempt + 1))
echo "OpenTofu ${stack} apply hit a transient Kubernetes API/OpenAPI error; waiting for API stability before retry ${attempt}/${max_attempts}..." >&2
rm -f "${output_file}"
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
sleep "${retry_sleep}"
done
}
run_tofu_stack() {
local stack="$1"
local auto_approve="${LAB_AUTO_APPROVE:-true}"
@ -595,7 +642,7 @@ run_tofu_stack() {
adopt_apps_existing_resources
fi
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
tofu -chdir="${REPO_ROOT}/${stack}" apply "${apply_args[@]}"
tofu_apply_with_kubernetes_retry "${stack}" "${apply_args[@]}"
}
run_tofu_plan_stack() {