-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeploy.sh
More file actions
executable file
·2800 lines (2416 loc) · 80 KB
/
deploy.sh
File metadata and controls
executable file
·2800 lines (2416 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
BOOTSTRAP_MONITOR_PID=""
ACTIVE_CHILD_PID=""
UPGRADE_SHOULD_RUN="false"
stop_bootstrap_background_monitor() {
if [[ -n "${BOOTSTRAP_MONITOR_PID}" ]]; then
kill "${BOOTSTRAP_MONITOR_PID}" >/dev/null 2>&1 || true
wait "${BOOTSTRAP_MONITOR_PID}" 2>/dev/null || true
BOOTSTRAP_MONITOR_PID=""
fi
}
handle_interrupt() {
printf '\n' >&2
if [[ -n "${ACTIVE_CHILD_PID}" ]]; then
kill "${ACTIVE_CHILD_PID}" >/dev/null 2>&1 || true
wait "${ACTIVE_CHILD_PID}" 2>/dev/null || true
ACTIVE_CHILD_PID=""
fi
stop_bootstrap_background_monitor
log_warn "Interrupted."
log_warn "No further deployment actions will be taken."
exit 130
}
trap handle_interrupt INT TERM
ACTION="${1:-apply}"
shift || true
workspace=""
destroy_workspace=""
upgrade_workspace=""
TFVARS_FILE="${TFVARS_FILE:-terraform.tfvars.json}"
OUT_DIR="${OUT_DIR:-out}"
DEPLOYMENT_HISTORY_DIR="${OUT_DIR}/deployment-history"
INVENTORY_PATH="${OUT_DIR}/inventory.yml"
ANSIBLE_VARS_PATH="${OUT_DIR}/ansible-vars.yml"
KUBECONFIG_PATH="${OUT_DIR}/kubeconfig"
PROXMOX_SSH_KEY_PATH="${PROXMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}"
PROXMOX_KEYCHAIN_SERVICE="${PROXMOX_KEYCHAIN_SERVICE:-proxmox-kubeadm-deployer}"
BOOTSTRAP_SSH_TIMEOUT_SECS="${BOOTSTRAP_SSH_TIMEOUT_SECS:-90}"
BOOTSTRAP_SSH_SLEEP_SECS="${BOOTSTRAP_SSH_SLEEP_SECS:-3}"
BOOTSTRAP_SSH_INITIAL_GRACE_SECS="${BOOTSTRAP_SSH_INITIAL_GRACE_SECS:-10}"
BOOTSTRAP_SSH_CONNECT_TIMEOUT_SECS="${BOOTSTRAP_SSH_CONNECT_TIMEOUT_SECS:-3}"
BOOTSTRAP_AUTO_REPLACE_UNREACHABLE="${BOOTSTRAP_AUTO_REPLACE_UNREACHABLE:-false}"
BOOTSTRAP_AUTO_REPLACE_MAX_ATTEMPTS="${BOOTSTRAP_AUTO_REPLACE_MAX_ATTEMPTS:-1}"
ANSIBLE_VERBOSITY="${ANSIBLE_VERBOSITY:-}"
SKIP_BOOTSTRAP_SSH_PREFLIGHT="${SKIP_BOOTSTRAP_SSH_PREFLIGHT:-false}"
BOOTSTRAP_BACKGROUND_MONITOR="${BOOTSTRAP_BACKGROUND_MONITOR:-true}"
BOOTSTRAP_BACKGROUND_MONITOR_INTERVAL_SECS="${BOOTSTRAP_BACKGROUND_MONITOR_INTERVAL_SECS:-20}"
PENDING_SSH_HOSTS=()
COLOR_RESET=""
COLOR_CYAN=""
COLOR_BLUE=""
COLOR_GREEN=""
COLOR_YELLOW=""
COLOR_RED=""
COLOR_DIM=""
COLOR_BOLD=""
init_colors() {
if [[ -t 1 && "${TERM:-}" != "dumb" ]]; then
COLOR_RESET=$'\033[0m'
COLOR_CYAN=$'\033[36m'
COLOR_BLUE=$'\033[34m'
COLOR_GREEN=$'\033[32m'
COLOR_YELLOW=$'\033[33m'
COLOR_RED=$'\033[31m'
COLOR_DIM=$'\033[2m'
COLOR_BOLD=$'\033[1m'
fi
}
log_step() {
printf '%s==>%s %s\n' "${COLOR_CYAN}${COLOR_BOLD}" "${COLOR_RESET}" "$*"
}
log_success() {
printf '%s%s%s\n' "${COLOR_GREEN}${COLOR_BOLD}" "$*" "${COLOR_RESET}"
}
log_info() {
printf '%s%s%s\n' "${COLOR_BLUE}" "$*" "${COLOR_RESET}"
}
log_warn() {
printf '%s%s%s\n' "${COLOR_YELLOW}${COLOR_BOLD}" "$*" "${COLOR_RESET}" >&2
}
log_error() {
printf '%s%s%s\n' "${COLOR_RED}${COLOR_BOLD}" "$*" "${COLOR_RESET}" >&2
}
log_item() {
printf ' %s-%s %s\n' "${COLOR_DIM}" "${COLOR_RESET}" "$*"
}
init_colors
platform_id() {
if [[ "$(uname -s)" == "Darwin" ]]; then
printf '%s\n' "macos"
return
fi
if [[ -r /etc/os-release ]]; then
. /etc/os-release
if [[ "${ID_LIKE:-}" == *debian* || "${ID:-}" == "ubuntu" || "${ID:-}" == "debian" ]]; then
printf '%s\n' "apt"
return
fi
if [[ "${ID_LIKE:-}" == *rhel* || "${ID_LIKE:-}" == *fedora* || "${ID:-}" == "rocky" || "${ID:-}" == "rhel" || "${ID:-}" == "fedora" ]]; then
printf '%s\n' "dnf"
return
fi
fi
printf '%s\n' "unknown"
}
print_optional_tool_suggestions() {
local platform
platform="$(platform_id)"
echo
log_info "Optional tools you might want:"
echo
optional_tool_entry "Cilium CLI" "cilium" "Troubleshoot and inspect Cilium networking and LoadBalancer state." \
"https://docs.cilium.io/en/stable/gettingstarted/k8s-install-default/" \
"$(optional_tool_install_hint "${platform}" "cilium")"
optional_tool_entry "kubectx" "kubectx" "Switch quickly between Kubernetes contexts on multi-cluster workstations." \
"https://github.com/ahmetb/kubectx" \
"$(optional_tool_install_hint "${platform}" "kubectx")"
optional_tool_entry "k9s" "k9s" "Inspect workloads, logs, and events from the terminal." \
"https://k9scli.io/" \
"$(optional_tool_install_hint "${platform}" "k9s")"
optional_tool_entry "Freelens" "freelens" "Desktop Kubernetes UI for cluster inspection." \
"https://freelensapp.github.io/" \
"$(optional_tool_install_hint "${platform}" "freelens")"
optional_tool_entry "pvecsictl" "pvecsictl" "Used to move local Proxmox CSI volumes between Proxmox nodes." \
"https://github.com/sergelogvinov/proxmox-csi-plugin" \
"$(optional_tool_install_hint "${platform}" "pvecsictl")"
}
optional_tool_install_hint() {
local platform="$1"
local tool="$2"
case "${platform}:${tool}" in
macos:cilium)
printf '%s\n' "brew install cilium-cli"
;;
macos:kubectx)
printf '%s\n' "brew install kubectx"
;;
macos:k9s)
printf '%s\n' "brew install k9s"
;;
macos:freelens)
printf '%s\n' "brew install --cask freelens"
;;
macos:pvecsictl)
printf '%s\n' "Prerequisite: Go. Then run: GOBIN=\"${HOME}/.local/bin\" go install github.com/sergelogvinov/proxmox-csi-plugin/cmd/pvecsictl@latest"
;;
apt:cilium|dnf:cilium|unknown:cilium)
printf '%s\n' "Follow the official Cilium CLI install instructions."
;;
apt:kubectx)
printf '%s\n' "Install from your distro package manager when available, or use the upstream project."
;;
dnf:kubectx|unknown:kubectx)
printf '%s\n' "Install from your distro package manager when available, or use the upstream project."
;;
apt:k9s|dnf:k9s|unknown:k9s)
printf '%s\n' "Install from your distro package manager when available, or use the official project."
;;
apt:freelens|dnf:freelens|unknown:freelens)
printf '%s\n' "Use the official DEB, RPM, Flatpak, or Snap packages."
;;
apt:pvecsictl|dnf:pvecsictl|unknown:pvecsictl)
printf '%s\n' "Prerequisite: Go. Then run: GOBIN=\"${HOME}/.local/bin\" go install github.com/sergelogvinov/proxmox-csi-plugin/cmd/pvecsictl@latest"
;;
*)
printf '%s\n' "See the official project documentation."
;;
esac
}
optional_tool_installed() {
local tool="$1"
case "${tool}" in
freelens)
if command -v freelens >/dev/null 2>&1 || command -v Freelens >/dev/null 2>&1; then
return 0
fi
[[ -d "/Applications/Freelens.app" || -d "${HOME}/Applications/Freelens.app" ]]
;;
*)
command -v "${tool}" >/dev/null 2>&1
;;
esac
}
optional_tool_entry() {
local label="$1"
local command_name="$2"
local description="$3"
local link="$4"
local install_hint="$5"
local status_text status_color
if optional_tool_installed "${command_name}"; then
status_text="installed"
status_color="${COLOR_GREEN}"
else
status_text="not installed"
status_color="${COLOR_YELLOW}"
fi
if [[ -n "${status_color}" ]]; then
log_item "${label}: ${description} [${status_color}${status_text}${COLOR_RESET}]"
else
log_item "${label}: ${description} [${status_text}]"
fi
echo " ${install_hint}"
echo " ${link}"
}
prompt_yes_no() {
local question="$1"
local default="${2:-false}"
local label="y/N"
if [[ "${default}" == "true" ]]; then
label="Y/n"
fi
while true; do
local reply lowered
read -r -p "${question} [${label}]: " reply
lowered="$(printf '%s' "${reply}" | tr '[:upper:]' '[:lower:]')"
if [[ -z "${lowered}" ]]; then
[[ "${default}" == "true" ]]
return
fi
case "${lowered}" in
y|yes) return 0 ;;
n|no) return 1 ;;
esac
echo "Enter yes or no."
done
}
install_hint() {
local command_name="$1"
local platform
platform="$(platform_id)"
case "${platform}:${command_name}" in
macos:tofu)
printf '%s\n' "Install it with: brew install opentofu"
;;
macos:freelens)
printf '%s\n' "Install it with: brew install --cask freelens"
;;
macos:ansible-playbook|macos:ansible-inventory)
printf '%s\n' "Install it with: brew install ansible"
;;
macos:kubectl)
printf '%s\n' "Install it with: brew install kubectl"
;;
macos:kubectx)
printf '%s\n' "Install it with: brew install kubectx"
;;
macos:k9s)
printf '%s\n' "Install it with: brew install k9s"
;;
macos:pvecsictl)
printf '%s\n' "Install it with Go: GOBIN=\"${HOME}/.local/bin\" go install github.com/sergelogvinov/proxmox-csi-plugin/cmd/pvecsictl@latest"
;;
macos:jq)
printf '%s\n' "Install it with: brew install jq"
;;
macos:ssh-copy-id)
printf '%s\n' "Install it with: brew install ssh-copy-id"
;;
macos:python3)
printf '%s\n' "Install it with: brew install python"
;;
apt:tofu)
printf '%s\n' "Install OpenTofu (`tofu`) using the official OpenTofu apt repository."
;;
apt:freelens)
printf '%s\n' "Optional: install Freelens using the official DEB package, or use Flatpak/Snap: https://freelensapp.github.io/"
;;
apt:ansible-playbook|apt:ansible-inventory)
printf '%s\n' "Install it with: sudo apt install -y ansible"
;;
apt:kubectl)
printf '%s\n' "Install it with: sudo apt install -y kubectl"
;;
apt:kubectx)
printf '%s\n' "Optional: install it with: sudo apt install -y kubectx"
;;
apt:k9s)
printf '%s\n' "Optional: install k9s from your preferred package source or https://k9scli.io/"
;;
apt:pvecsictl)
printf '%s\n' "Optional: install it with Go: GOBIN=\"${HOME}/.local/bin\" go install github.com/sergelogvinov/proxmox-csi-plugin/cmd/pvecsictl@latest"
;;
apt:jq)
printf '%s\n' "Install it with: sudo apt install -y jq"
;;
apt:ssh-copy-id|apt:ssh|apt:ssh-keygen)
printf '%s\n' "Install it with: sudo apt install -y openssh-client"
;;
apt:python3)
printf '%s\n' "Install it with: sudo apt install -y python3"
;;
dnf:tofu)
printf '%s\n' "Install OpenTofu (`tofu`) using the official OpenTofu dnf repository."
;;
dnf:freelens)
printf '%s\n' "Optional: install Freelens using the official RPM package, or use Flatpak/Snap: https://freelensapp.github.io/"
;;
dnf:ansible-playbook|dnf:ansible-inventory)
printf '%s\n' "Install it with: sudo dnf install -y ansible"
;;
dnf:kubectl)
printf '%s\n' "Install it with: sudo dnf install -y kubectl"
;;
dnf:kubectx)
printf '%s\n' "Optional: install kubectx from your preferred package source or https://github.com/ahmetb/kubectx"
;;
dnf:k9s)
printf '%s\n' "Optional: install k9s from your preferred package source or https://k9scli.io/"
;;
dnf:pvecsictl)
printf '%s\n' "Optional: install it with Go: GOBIN=\"${HOME}/.local/bin\" go install github.com/sergelogvinov/proxmox-csi-plugin/cmd/pvecsictl@latest"
;;
dnf:jq)
printf '%s\n' "Install it with: sudo dnf install -y jq"
;;
dnf:ssh-copy-id|dnf:ssh|dnf:ssh-keygen)
printf '%s\n' "Install it with: sudo dnf install -y openssh-clients"
;;
dnf:python3)
printf '%s\n' "Install it with: sudo dnf install -y python3"
;;
esac
}
install_required_command() {
local command_name="$1"
local platform
platform="$(platform_id)"
case "${platform}:${command_name}" in
macos:tofu)
brew install opentofu
;;
macos:ansible-playbook|macos:ansible-inventory)
brew install ansible
;;
macos:kubectl)
brew install kubectl
;;
macos:jq)
brew install jq
;;
macos:ssh-copy-id)
brew install ssh-copy-id
;;
macos:python3)
brew install python
;;
apt:ansible-playbook|apt:ansible-inventory)
sudo apt install -y ansible
;;
apt:jq)
sudo apt install -y jq
;;
apt:ssh-copy-id|apt:ssh|apt:ssh-keygen)
sudo apt install -y openssh-client
;;
apt:python3)
sudo apt install -y python3
;;
dnf:ansible-playbook|dnf:ansible-inventory)
sudo dnf install -y ansible
;;
dnf:jq)
sudo dnf install -y jq
;;
dnf:ssh-copy-id|dnf:ssh|dnf:ssh-keygen)
sudo dnf install -y openssh-clients
;;
dnf:python3)
sudo dnf install -y python3
;;
*)
return 1
;;
esac
}
prompt_install_required_command() {
local command_name="$1"
if [[ ! -t 0 ]]; then
return 1
fi
if ! prompt_yes_no "Install missing required command '${command_name}' now?" true; then
return 1
fi
if install_required_command "${command_name}"; then
return 0
fi
return 1
}
need() {
if command -v "$1" >/dev/null 2>&1; then
return 0
fi
echo "Missing required command: $1" >&2
local hint
hint="$(install_hint "$1" || true)"
if prompt_install_required_command "$1"; then
if command -v "$1" >/dev/null 2>&1; then
return 0
fi
echo "Tried to install '$1', but it is still unavailable in PATH." >&2
fi
if [[ -n "${hint}" ]]; then
echo "${hint}" >&2
fi
exit 1
}
ssh_probe_options() {
cat <<EOF
-o BatchMode=yes
-o StrictHostKeyChecking=no
-o UserKnownHostsFile=/dev/null
-o GlobalKnownHostsFile=/dev/null
-o ConnectTimeout=${BOOTSTRAP_SSH_CONNECT_TIMEOUT_SECS}
-o ConnectionAttempts=1
EOF
}
ensure_dirs() {
mkdir -p "${OUT_DIR}/ssh" "${DEPLOYMENT_HISTORY_DIR}"
}
sanitize_workspace_name() {
local raw="${1:-default}"
raw="$(printf '%s' "${raw}" | tr '[:upper:]' '[:lower:]')"
raw="$(printf '%s' "${raw}" | sed -E 's/[^a-z0-9._-]+/-/g; s/^-+//; s/-+$//')"
if [[ -z "${raw}" ]]; then
raw="default"
fi
printf '%s\n' "${raw}"
}
ensure_tfvars() {
if [[ ! -f "${TFVARS_FILE}" ]]; then
echo "Missing ${TFVARS_FILE}."
echo "Run ./deploy.sh configure first."
exit 1
fi
}
ensure_rendered_outputs_current() {
local workspace snapshot_path
if [[ ! -f "${INVENTORY_PATH}" || ! -f "${ANSIBLE_VARS_PATH}" ]]; then
echo "Missing generated inventory or ansible vars."
echo "Run ./deploy.sh apply first so Terraform can render them."
exit 1
fi
workspace="$(current_workspace_name)"
snapshot_path="$(workspace_last_applied_tfvars_path "${workspace}")"
if [[ ! -f "${snapshot_path}" ]]; then
echo "Missing last applied deployment snapshot for workspace ${workspace}."
echo "Run ./deploy.sh apply first so Terraform can render fresh outputs."
exit 1
fi
if ! cmp -s "${TFVARS_FILE}" "${snapshot_path}"; then
echo "Current ${TFVARS_FILE} does not match the last applied deployment snapshot for workspace ${workspace}."
echo "Run ./deploy.sh apply to refresh the rendered outputs before bootstrap."
exit 1
fi
}
validate_tfvars() {
need python3
ensure_tfvars
python3 scripts/validate_config.py --file "${TFVARS_FILE}" --fix
}
read_tfvar() {
python3 - "$TFVARS_FILE" "$1" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
value = data
for part in sys.argv[2].split("."):
value = value.get(part) if isinstance(value, dict) else None
print("" if value is None else value)
PY
}
read_tfvar_from_file() {
python3 - "$1" "$2" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
value = data
for part in sys.argv[2].split("."):
value = value.get(part) if isinstance(value, dict) else None
print("" if value is None else value)
PY
}
current_workspace_name() {
local cluster_name
cluster_name="$(read_tfvar cluster_name)"
sanitize_workspace_name "${cluster_name}"
}
workspace_history_dir() {
local workspace="$1"
printf '%s/%s\n' "${DEPLOYMENT_HISTORY_DIR}" "${workspace}"
}
workspace_history_ssh_dir() {
local workspace="$1"
printf '%s/ssh\n' "$(workspace_history_dir "${workspace}")"
}
workspace_last_applied_tfvars_path() {
local workspace="$1"
printf '%s/last-applied.tfvars.json\n' "$(workspace_history_dir "${workspace}")"
}
snapshot_workspace_ssh_key() {
local workspace="$1"
local ssh_history_dir
ssh_history_dir="$(workspace_history_ssh_dir "${workspace}")"
mkdir -p "${ssh_history_dir}"
if [[ -f "${OUT_DIR}/ssh/id_cluster_ed25519" ]]; then
cp "${OUT_DIR}/ssh/id_cluster_ed25519" "${ssh_history_dir}/id_cluster_ed25519"
chmod 600 "${ssh_history_dir}/id_cluster_ed25519"
fi
if [[ -f "${OUT_DIR}/ssh/id_cluster_ed25519.pub" ]]; then
cp "${OUT_DIR}/ssh/id_cluster_ed25519.pub" "${ssh_history_dir}/id_cluster_ed25519.pub"
chmod 644 "${ssh_history_dir}/id_cluster_ed25519.pub"
fi
}
restore_shared_cluster_ssh_key_from_history() {
local exclude_workspace="${1:-}"
local workspace ssh_history_dir
while IFS= read -r workspace; do
[[ -z "${workspace}" ]] && continue
[[ -n "${exclude_workspace}" && "${workspace}" == "${exclude_workspace}" ]] && continue
ssh_history_dir="$(workspace_history_ssh_dir "${workspace}")"
if [[ -f "${ssh_history_dir}/id_cluster_ed25519" && -f "${ssh_history_dir}/id_cluster_ed25519.pub" ]]; then
mkdir -p "${OUT_DIR}/ssh"
cp "${ssh_history_dir}/id_cluster_ed25519" "${OUT_DIR}/ssh/id_cluster_ed25519"
cp "${ssh_history_dir}/id_cluster_ed25519.pub" "${OUT_DIR}/ssh/id_cluster_ed25519.pub"
chmod 600 "${OUT_DIR}/ssh/id_cluster_ed25519"
chmod 644 "${OUT_DIR}/ssh/id_cluster_ed25519.pub"
return 0
fi
done < <(list_recorded_workspaces)
return 1
}
list_recorded_workspaces() {
if [[ ! -d "${DEPLOYMENT_HISTORY_DIR}" ]]; then
return 0
fi
local workspace_dir workspace snapshot_path
while IFS= read -r workspace_dir; do
[[ -z "${workspace_dir}" ]] && continue
workspace="$(basename "${workspace_dir}")"
snapshot_path="$(workspace_last_applied_tfvars_path "${workspace}")"
if [[ -f "${snapshot_path}" ]] && workspace_has_state_resources "${workspace}"; then
printf '%s\n' "${workspace}"
fi
done < <(find "${DEPLOYMENT_HISTORY_DIR}" -mindepth 1 -maxdepth 1 -type d | sort)
}
workspace_has_state_resources() {
local workspace="$1"
local state_path address
state_path="$(workspace_state_path "${workspace}")"
if [[ ! -f "${state_path}" ]]; then
return 1
fi
while IFS= read -r address; do
[[ -z "${address}" ]] && continue
if [[ "${address}" == proxmox_download_file.cloud_image* ]]; then
continue
fi
return 0
done < <(tofu state list -state="${state_path}" 2>/dev/null || true)
return 1
}
describe_workspace() {
local workspace="$1"
local tfvars_path cluster_name os_family os_version
tfvars_path="$(workspace_last_applied_tfvars_path "${workspace}")"
if [[ -f "${tfvars_path}" ]]; then
cluster_name="$(python3 - "${tfvars_path}" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
print(data.get("cluster_name", ""))
PY
)"
os_family="$(python3 - "${tfvars_path}" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
print(data.get("os_family", ""))
PY
)"
os_version="$(python3 - "${tfvars_path}" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
print(data.get("os_version", ""))
PY
)"
printf '%s (%s, %s %s)\n' "${workspace}" "${cluster_name:-unknown}" "${os_family:-unknown}" "${os_version:-unknown}"
return
fi
printf '%s\n' "${workspace}"
}
workspace_cluster_name() {
local workspace="$1"
local tfvars_path cluster_name
tfvars_path="$(workspace_last_applied_tfvars_path "${workspace}")"
if [[ -f "${tfvars_path}" ]]; then
cluster_name="$(python3 - "${tfvars_path}" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as fh:
data = json.load(fh)
print(data.get("cluster_name", ""))
PY
)"
if [[ -n "${cluster_name}" ]]; then
printf '%s\n' "${cluster_name}"
return
fi
fi
printf '%s\n' "${workspace}"
}
proxmox_keychain_account() {
local api_url ssh_host ssh_user
api_url="$(read_tfvar proxmox_api_url)"
ssh_user="$(read_tfvar proxmox_username)"
ssh_host="$(python3 - "${api_url}" <<'PY'
import sys, urllib.parse
parsed = urllib.parse.urlparse(sys.argv[1])
print(parsed.hostname or "")
PY
)"
printf '%s\n' "${ssh_user}@${ssh_host}"
}
can_use_keychain() {
[[ "$(uname -s)" == "Darwin" ]] && command -v security >/dev/null 2>&1
}
load_password_from_keychain() {
local account
account="$(proxmox_keychain_account)"
security find-generic-password \
-s "${PROXMOX_KEYCHAIN_SERVICE}" \
-a "${account}" \
-w 2>/dev/null || true
}
save_password_to_keychain() {
local account
account="$(proxmox_keychain_account)"
security add-generic-password \
-U \
-s "${PROXMOX_KEYCHAIN_SERVICE}" \
-a "${account}" \
-w "${PROXMOX_PASSWORD}" >/dev/null
}
load_proxmox_password() {
if [[ -z "${PROXMOX_PASSWORD:-}" ]]; then
if can_use_keychain; then
PROXMOX_PASSWORD="$(load_password_from_keychain)"
fi
if [[ -z "${PROXMOX_PASSWORD:-}" ]]; then
if [[ ! -t 0 ]]; then
echo "Missing PROXMOX_PASSWORD and no interactive terminal is available." >&2
exit 1
fi
read -r -s -p "Proxmox password: " PROXMOX_PASSWORD
echo
export PROXMOX_PASSWORD
if can_use_keychain; then
local reply
read -r -p "Save the Proxmox password in macOS Keychain for reuse? [Y/n]: " reply
case "${reply:-Y}" in
y|Y|yes|YES|"")
save_password_to_keychain
;;
esac
fi
fi
fi
export PROXMOX_PASSWORD
export TF_VAR_proxmox_password="${PROXMOX_PASSWORD}"
}
ensure_local_ssh_key() {
need ssh-keygen
local pubkey_path="${PROXMOX_SSH_KEY_PATH}.pub"
if [[ ! -f "${PROXMOX_SSH_KEY_PATH}" || ! -f "${pubkey_path}" ]]; then
mkdir -p "$(dirname "${PROXMOX_SSH_KEY_PATH}")"
ssh-keygen -t ed25519 -f "${PROXMOX_SSH_KEY_PATH}" -N ""
fi
}
setup_proxmox_ssh_access() {
need python3
need ssh-copy-id
ensure_tfvars
ensure_local_ssh_key
local api_url ssh_host ssh_user
api_url="$(read_tfvar proxmox_api_url)"
ssh_user="$(read_tfvar proxmox_username)"
ssh_host="$(python3 - "${api_url}" <<'PY'
import sys, urllib.parse
parsed = urllib.parse.urlparse(sys.argv[1])
print(parsed.hostname or "")
PY
)"
ssh_user="${ssh_user%@*}"
if [[ -z "${ssh_host}" || -z "${ssh_user}" ]]; then
echo "Unable to determine Proxmox SSH target from ${TFVARS_FILE}." >&2
exit 1
fi
echo "==> Installing ${PROXMOX_SSH_KEY_PATH}.pub on ${ssh_user}@${ssh_host}"
ssh-copy-id -i "${PROXMOX_SSH_KEY_PATH}.pub" "${ssh_user}@${ssh_host}"
}
proxmox_ssh_host() {
local api_url
api_url="$(read_tfvar proxmox_api_url)"
python3 - "${api_url}" <<'PY'
import sys, urllib.parse
parsed = urllib.parse.urlparse(sys.argv[1])
print(parsed.hostname or "")
PY
}
proxmox_ssh_user() {
local ssh_user
ssh_user="$(read_tfvar proxmox_username)"
printf '%s\n' "${ssh_user%@*}"
}
ensure_local_snippets_dir() {
need ssh
need python3
local snippets_datastore ssh_host ssh_user ssh_target
snippets_datastore="$(read_tfvar snippets_datastore)"
if [[ "${snippets_datastore}" != "local" ]]; then
return 0
fi
ssh_host="$(proxmox_ssh_host)"
ssh_user="$(proxmox_ssh_user)"
ssh_target="${ssh_user}@${ssh_host}"
echo "==> Ensuring Proxmox local snippets directory exists"
if ssh -i "${PROXMOX_SSH_KEY_PATH}" \
-o BatchMode=yes \
-o StrictHostKeyChecking=no \
-o ConnectTimeout=5 \
"${ssh_target}" "install -d -m 0755 /var/lib/vz/snippets" >/dev/null 2>&1; then
return 0
fi
echo "Unable to create /var/lib/vz/snippets on ${ssh_target} automatically." >&2
echo "Either run ./deploy.sh proxmox-ssh-setup first, or create it manually on the Proxmox host:" >&2
echo " sudo install -d -m 0755 /var/lib/vz/snippets" >&2
exit 1
}
tf_init() {
need tofu
ensure_dirs
validate_tfvars
load_proxmox_password
tofu init
}
select_workspace() {
local workspace="$1"
if tofu workspace select "${workspace}" >/dev/null 2>&1; then
return 0
fi
tofu workspace new "${workspace}" >/dev/null
}
snapshot_last_applied_tfvars() {
local workspace="${1}"
local target_dir target_path
ensure_dirs
if [[ ! -f "${TFVARS_FILE}" ]]; then
return
fi
target_dir="$(workspace_history_dir "${workspace}")"
target_path="$(workspace_last_applied_tfvars_path "${workspace}")"
mkdir -p "${target_dir}"
cp "${TFVARS_FILE}" "${target_path}"
cp "${TFVARS_FILE}" "${target_dir}/tfvars.$(date +%Y%m%d%H%M%S).json"
snapshot_workspace_ssh_key "${workspace}"
}
resolve_destroy_tfvars() {
local workspace="$1"
local path
path="$(workspace_last_applied_tfvars_path "${workspace}")"
if [[ -f "${path}" ]]; then
printf '%s\n' "${path}"
return
fi
printf '%s\n' "${TFVARS_FILE}"
}
state_resource_count() {
local state_path="$1"
python3 - "${state_path}" <<'PY'
import json, os, sys
path = sys.argv[1]
if not os.path.exists(path):
print(0)
raise SystemExit(0)
try:
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
print(len(data.get("resources", [])))
except Exception:
print(0)
PY
}
workspace_state_path() {
local workspace="$1"
if [[ "${workspace}" == "default" ]]; then
printf '%s\n' "terraform.tfstate"
return
fi
printf '%s\n' "terraform.tfstate.d/${workspace}/terraform.tfstate"
}
resolve_destroy_state_args() {
local workspace="$1"
local workspace_state root_state workspace_count root_count
workspace_state="$(workspace_state_path "${workspace}")"
root_state="terraform.tfstate"
workspace_count="$(state_resource_count "${workspace_state}")"
root_count="$(state_resource_count "${root_state}")"
if (( workspace_count > 0 )); then
return 0
fi
if [[ "${workspace}" != "default" ]] && (( root_count > 0 )); then
echo "==> Workspace ${workspace} is empty, but legacy root state still has resources. Falling back to terraform.tfstate." >&2
printf '%s\n' "-state=${root_state}"
fi
}
should_remove_cloud_image_on_destroy() {
local configured lowered
configured="${DESTROY_REMOVE_CLOUD_IMAGE:-}"
lowered="$(printf '%s' "${configured}" | tr '[:upper:]' '[:lower:]')"
case "${lowered}" in
1|true|y|yes)
return 0
;;
0|false|n|no)
return 1
;;
esac
if [[ ! -t 0 ]]; then
return 1
fi
printf '\n'
log_info "The cached cloud image can be kept on Proxmox to avoid re-downloading it later."
if prompt_yes_no "Also remove the cached cloud image from Proxmox?" false; then
return 0
fi
return 1
}
destroy_targets_preserving_cloud_image() {
local workspace="$1"
local destroy_state_arg="$2"
local state_path address
local targets=()
state_path="$(workspace_state_path "${workspace}")"
if [[ -n "${destroy_state_arg}" ]]; then
state_path="${destroy_state_arg#-state=}"
fi
if [[ ! -f "${state_path}" ]]; then
return 0
fi
while IFS= read -r address; do
[[ -z "${address}" ]] && continue
if [[ "${address}" == proxmox_download_file.cloud_image* ]]; then
continue
fi
targets+=("-target=${address}")
done < <(tofu state list -state="${state_path}" 2>/dev/null || true)
printf '%s\n' "${targets[@]}"
}
run_destroy_preserving_cloud_image() {
local destroy_workspace="$1"
local destroy_tfvars="$2"
local destroy_state_arg="$3"
shift 3
local state_path temp_state
local image_addresses=()
local address
state_path="$(workspace_state_path "${destroy_workspace}")"
if [[ -n "${destroy_state_arg}" ]]; then
state_path="${destroy_state_arg#-state=}"
fi
if [[ ! -f "${state_path}" ]]; then
log_warn "No workspace state file was found for ${destroy_workspace}; running a normal destroy."
if [[ -n "${destroy_state_arg}" ]]; then
tofu destroy -refresh=false "${destroy_state_arg}" -var-file="${destroy_tfvars}" -auto-approve "$@"
else