fix: retry no-refresh OpenTofu fallback

This commit is contained in:
juvenal.diaz 2026-10-07 12:48:57 -06:00
parent 49304e2674
commit 3fe294614c
1 changed files with 24 additions and 7 deletions

View File

@ -581,6 +581,8 @@ tofu_apply_with_kubernetes_retry() {
local max_attempts="${LAB_TOFU_K8S_APPLY_RETRIES:-3}"
local retry_sleep="${LAB_TOFU_K8S_APPLY_RETRY_SLEEP_SECONDS:-30}"
local refresh_fallback="${LAB_TOFU_K8S_REFRESH_FALSE_FALLBACK:-true}"
local refresh_fallback_attempts="${LAB_TOFU_K8S_REFRESH_FALSE_RETRIES:-${LAB_TOFU_K8S_APPLY_RETRIES:-3}}"
local retry_error_pattern='cannot get OpenAPI|failed get OpenAPI spec|context deadline exceeded|TLS handshake timeout|connection refused|unexpected EOF|server is currently unable|bad record MAC|failed to query with labels|unexpected error when reading response body|unable to build kubernetes objects from release manifest'
local attempt=1
local status=0
local output_file
@ -602,20 +604,35 @@ tofu_apply_with_kubernetes_retry() {
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|bad record MAC|failed to query with labels|unexpected error when reading response body' \
"${output_file}"; then
if ! grep -Eiq "${retry_error_pattern}" "${output_file}"; then
rm -f "${output_file}"
return "${status}"
fi
if ((attempt >= max_attempts)); then
if truthy "${refresh_fallback}"; then
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI read errors after ${attempt} attempt(s); trying one guarded -refresh=false apply." >&2
rm -f "${output_file}"
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
tofu -chdir="${REPO_ROOT}/${stack}" apply -refresh=false "$@"
return $?
local refresh_attempt=1
while true; do
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI read errors after ${attempt} attempt(s); trying guarded -refresh=false apply ${refresh_attempt}/${refresh_fallback_attempts}." >&2
ensure_kubernetes_api_ready_for_tofu_stack "${stack}"
output_file="$(mktemp "${TMPDIR:-/tmp}/homelab-tofu-refresh-false-apply.XXXXXX")"
set +e
tofu -chdir="${REPO_ROOT}/${stack}" apply -refresh=false "$@" 2>&1 | tee "${output_file}"
status="${PIPESTATUS[0]}"
set -e
if ((status == 0)); then
rm -f "${output_file}"
return 0
fi
if ! grep -Eiq "${retry_error_pattern}" "${output_file}" || ((refresh_attempt >= refresh_fallback_attempts)); then
rm -f "${output_file}"
return "${status}"
fi
refresh_attempt=$((refresh_attempt + 1))
rm -f "${output_file}"
sleep "${retry_sleep}"
done
fi
echo "OpenTofu ${stack} apply still hit Kubernetes API/OpenAPI errors after ${attempt} attempt(s)." >&2
rm -f "${output_file}"