-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkns
More file actions
953 lines (813 loc) · 25.2 KB
/
Copy pathkns
File metadata and controls
953 lines (813 loc) · 25.2 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
#!/usr/bin/env bash
# kns - Kubernetes Namespace/Context Switcher
# Automatically switches kubectl context based on current directory
set -euo pipefail
# Configuration
KNS_CONFIG_DIR="${KNS_CONFIG_DIR:-$HOME/.kns}"
KNS_CONFIG_FILE="$KNS_CONFIG_DIR/config"
KNS_LOCAL_FILE=".kns.conf"
# Ensure config directory exists
mkdir -p "$KNS_CONFIG_DIR"
# Main command dispatcher
main() {
local cmd="${1:-help}"
shift || true
case "$cmd" in
set)
cmd_set "$@"
;;
current)
cmd_current "$@"
;;
use)
cmd_use "$@"
;;
list)
cmd_list "$@"
;;
link)
cmd_link "$@"
;;
unlink)
cmd_unlink "$@"
;;
gp|gs|gd|ns)
cmd_kubectl "$cmd" "$@"
;;
sp)
cmd_set_pod "$@"
;;
sc)
cmd_set_container "$@"
;;
gc)
cmd_get_containers "$@"
;;
exec)
cmd_exec "$@"
;;
cp)
cmd_copy "$@"
;;
sh)
cmd_shell "$@"
;;
help|--help|-h)
show_help
;;
*)
echo "Unknown command: $cmd" >&2
show_help
exit 1
;;
esac
}
# Find .kns.conf file in current or parent directories
find_context_file() {
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
echo "$dir/$KNS_LOCAL_FILE"
return 0
fi
dir=$(dirname "$dir")
done
# Fallback: check home directory for default context
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
echo "$HOME/$KNS_LOCAL_FILE"
return 0
fi
return 1
}
# Source all .kns.conf files from current directory up to root/home
# This merges values from multiple .kns.conf files
source_all_context_files() {
# Clear any existing values
unset KNS_CONTEXT KNS_NAMESPACE KNS_POD KNS_CONTAINER
# Collect all .kns.conf files from current up to root
local files=()
local dir="$PWD"
# First, collect files from current directory up to root
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
# Add home directory file if it exists
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
files+=("$HOME/$KNS_LOCAL_FILE")
fi
# Source files in reverse order (parent/home first, then current)
# This way current directory values override parent values
local i
for ((i=${#files[@]}-1; i>=0; i--)); do
if [[ -f "${files[i]}" ]]; then
source "${files[i]}" 2>/dev/null || true
fi
done
# Return the first file found (closest to current directory) for display purposes
if [[ ${#files[@]} -gt 0 ]]; then
echo "${files[0]}"
return 0
fi
return 1
}
# Read context from file
read_context() {
local file="$1"
if [[ -f "$file" ]]; then
source "$file"
echo "${KNS_CONTEXT:-}:${KNS_NAMESPACE:-}"
fi
}
# Read pod/container from .kns.conf file
read_pod_config() {
local file="$1"
if [[ -f "$file" ]]; then
source "$file" 2>/dev/null || true
echo "${KNS_POD:-}:${KNS_CONTAINER:-}"
fi
}
# Set context for current directory
cmd_set() {
local context="${1:-}"
local namespace="${2:-}"
if [[ -z "$context" ]]; then
echo "Usage: kns set <context> [namespace]" >&2
exit 1
fi
local file="$PWD/$KNS_LOCAL_FILE"
local existing_pod=""
local existing_container=""
# Preserve existing pod/container if file exists
if [[ -f "$file" ]]; then
local pod_config=$(read_pod_config "$file")
IFS=':' read -r existing_pod existing_container <<< "$pod_config"
fi
cat > "$file" <<EOF
# Auto-generated by kns
KNS_CONTEXT="$context"
KNS_NAMESPACE="$namespace"
EOF
# Add pod/container if they exist
if [[ -n "$existing_pod" ]]; then
echo "KNS_POD=\"$existing_pod\"" >> "$file"
fi
if [[ -n "$existing_container" ]]; then
echo "KNS_CONTAINER=\"$existing_container\"" >> "$file"
fi
echo "Set context for $(pwd):"
echo " Context: $context"
[[ -n "$namespace" ]] && echo " Namespace: $namespace"
# Auto-switch if in this directory
cmd_use "$context" "$namespace"
}
# Get current context
cmd_current() {
# Check for manual override first
local manual_override_file="$KNS_CONFIG_DIR/manual_override"
if [[ -f "$manual_override_file" ]]; then
local KNS_MANUAL_OVERRIDE=""
local KNS_MANUAL_CONTEXT=""
local KNS_MANUAL_NAMESPACE=""
source "$manual_override_file" 2>/dev/null || true
if [[ "${KNS_MANUAL_OVERRIDE:-}" == "1" ]] && [[ -n "${KNS_MANUAL_CONTEXT:-}" ]]; then
echo "Source: Manual override (from 'kns use' command)"
echo "Context: ${KNS_MANUAL_CONTEXT}"
[[ -n "${KNS_MANUAL_NAMESPACE:-}" ]] && echo "Namespace: ${KNS_MANUAL_NAMESPACE}"
return 0
fi
fi
# Check for .kns.conf file(s) and merge values from all found files
# Source all files directly (not in subshell)
unset KNS_CONTEXT KNS_NAMESPACE KNS_POD KNS_CONTAINER
# Collect all .kns.conf files from current directory up to root
local files=()
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
files+=("$HOME/$KNS_LOCAL_FILE")
fi
if [[ ${#files[@]} -gt 0 ]]; then
# Source files in reverse order (parent/home first, then current)
local i
for ((i=${#files[@]}-1; i>=0; i--)); do
if [[ -f "${files[i]}" ]]; then
source "${files[i]}" 2>/dev/null || true
fi
done
local context_file="${files[0]}"
# Show all sources if multiple files were found
local dir="$PWD"
local found_files=()
# Collect all files
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
found_files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
found_files+=("$HOME/$KNS_LOCAL_FILE")
fi
if [[ ${#found_files[@]} -gt 1 ]]; then
echo "Source: ${found_files[*]} (merged)"
else
echo "Source: $context_file"
fi
if [[ -n "${KNS_CONTEXT:-}" ]]; then
echo "Context: $KNS_CONTEXT"
else
echo "Context: <not set>"
fi
if [[ -n "${KNS_NAMESPACE:-}" ]]; then
echo "Namespace: $KNS_NAMESPACE"
fi
if [[ -n "${KNS_POD:-}" ]]; then
echo "Pod: $KNS_POD"
fi
if [[ -n "${KNS_CONTAINER:-}" ]]; then
echo "Container: $KNS_CONTAINER"
fi
else
echo "No .kns.conf file found in current or parent directories"
exit 1
fi
}
# Use/switch context (temporarily overrides .kns.conf)
cmd_use() {
local context="${1:-}"
local namespace="${2:-}"
if [[ -z "$context" ]]; then
echo "Usage: kns use <context> [namespace]" >&2
exit 1
fi
# Check if kubectl is available
if ! command -v kubectl >/dev/null 2>&1; then
echo "Error: kubectl is not installed or not in PATH" >&2
exit 1
fi
# Switch kubectl context
if kubectl config use-context "$context" >/dev/null 2>&1; then
echo "Switched to context: $context"
# Set namespace if provided
if [[ -n "$namespace" ]]; then
kubectl config set-context "$context" --namespace="$namespace" >/dev/null 2>&1
echo "Set namespace: $namespace"
fi
# Write manual override to file so it persists across script invocations
# This will be cleared when directory changes (handled by kns.sh)
cat > "$KNS_CONFIG_DIR/manual_override" <<EOF
KNS_MANUAL_OVERRIDE=1
KNS_MANUAL_CONTEXT="$context"
KNS_MANUAL_NAMESPACE="${namespace:-}"
EOF
else
echo "Error: Context '$context' not found" >&2
exit 1
fi
}
# List all contexts
cmd_list() {
if ! command -v kubectl >/dev/null 2>&1; then
echo "Error: kubectl is not installed or not in PATH" >&2
exit 1
fi
echo "Available kubectl contexts:"
kubectl config get-contexts -o name | while read -r ctx; do
echo " - $ctx"
done
}
# Link current directory to context
cmd_link() {
local context="${1:-}"
local namespace="${2:-}"
if [[ -z "$context" ]]; then
echo "Usage: kns link <context> [namespace]" >&2
exit 1
fi
cmd_set "$context" "$namespace"
}
# Unlink current directory
cmd_unlink() {
local file="$PWD/$KNS_LOCAL_FILE"
if [[ -f "$file" ]]; then
rm "$file"
echo "Unlinked context from $(pwd)"
else
echo "No .kns.conf file found in current directory"
exit 1
fi
}
# Quick kubectl shortcuts
cmd_kubectl() {
local cmd="$1"
shift
# Auto-switch context if .kns.conf exists
auto_switch_context
case "$cmd" in
gp)
kubectl get pods "$@"
;;
gs)
kubectl get services "$@"
;;
gd)
kubectl get deployments "$@"
;;
ns)
kubectl get namespaces "$@"
;;
esac
}
# Auto-switch context based on current directory
auto_switch_context() {
# Check for manual override from 'kns use' command (stored in file)
local manual_override_file="$KNS_CONFIG_DIR/manual_override"
if [[ -f "$manual_override_file" ]]; then
local KNS_MANUAL_OVERRIDE=""
local KNS_MANUAL_CONTEXT=""
local KNS_MANUAL_NAMESPACE=""
source "$manual_override_file" 2>/dev/null || true
if [[ "${KNS_MANUAL_OVERRIDE:-}" == "1" ]] && [[ -n "${KNS_MANUAL_CONTEXT:-}" ]]; then
kubectl config use-context "$KNS_MANUAL_CONTEXT" >/dev/null 2>&1
if [[ -n "${KNS_MANUAL_NAMESPACE:-}" ]]; then
kubectl config set-context "$KNS_MANUAL_CONTEXT" --namespace="$KNS_MANUAL_NAMESPACE" >/dev/null 2>&1
fi
return 0
fi
fi
# No manual override, so use .kns.conf if available
# Source all files directly (not in subshell)
unset KNS_CONTEXT KNS_NAMESPACE KNS_POD KNS_CONTAINER
# Collect all .kns.conf files from current directory up to root
local files=()
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
files+=("$HOME/$KNS_LOCAL_FILE")
fi
if [[ ${#files[@]} -gt 0 ]]; then
# Source files in reverse order (parent/home first, then current)
local i
for ((i=${#files[@]}-1; i>=0; i--)); do
if [[ -f "${files[i]}" ]]; then
source "${files[i]}" 2>/dev/null || true
fi
done
if [[ -n "${KNS_CONTEXT:-}" ]]; then
kubectl config use-context "$KNS_CONTEXT" >/dev/null 2>&1
if [[ -n "${KNS_NAMESPACE:-}" ]]; then
kubectl config set-context "$KNS_CONTEXT" --namespace="$KNS_NAMESPACE" >/dev/null 2>&1
fi
fi
fi
# Note: Manual override file is only cleared on directory change (kns.sh)
}
# Set current pod
cmd_set_pod() {
local pod="${1:-}"
if [[ -z "$pod" ]]; then
echo "Usage: kns sp <pod-name>" >&2
exit 1
fi
local file="$PWD/$KNS_LOCAL_FILE"
local existing_context=""
local existing_namespace=""
local existing_container=""
# Preserve existing context/namespace/container if file exists
if [[ -f "$file" ]]; then
source "$file" 2>/dev/null || true
existing_context="${KNS_CONTEXT:-}"
existing_namespace="${KNS_NAMESPACE:-}"
existing_container="${KNS_CONTAINER:-}"
fi
# Auto-switch context if needed
auto_switch_context
# Verify pod exists
if ! kubectl get pod "$pod" >/dev/null 2>&1; then
echo "Error: Pod '$pod' not found" >&2
exit 1
fi
# Write/update config file
{
echo "# Auto-generated by kns"
if [[ -n "$existing_context" ]]; then
echo "KNS_CONTEXT=\"$existing_context\""
fi
if [[ -n "$existing_namespace" ]]; then
echo "KNS_NAMESPACE=\"$existing_namespace\""
fi
echo "KNS_POD=\"$pod\""
if [[ -n "$existing_container" ]]; then
echo "KNS_CONTAINER=\"$existing_container\""
fi
} > "$file"
echo "Set current pod: $pod"
}
# Set current container
cmd_set_container() {
local container="${1:-}"
if [[ -z "$container" ]]; then
echo "Usage: kns sc <container-name>" >&2
exit 1
fi
local file="$PWD/$KNS_LOCAL_FILE"
local existing_context=""
local existing_namespace=""
local existing_pod=""
# Preserve existing context/namespace/pod if file exists
if [[ -f "$file" ]]; then
source "$file" 2>/dev/null || true
existing_context="${KNS_CONTEXT:-}"
existing_namespace="${KNS_NAMESPACE:-}"
existing_pod="${KNS_POD:-}"
fi
if [[ -z "$existing_pod" ]]; then
echo "Error: Pod must be set first. Use 'kns sp <pod-name>' to set it." >&2
exit 1
fi
# Auto-switch context if needed
auto_switch_context
# Verify container exists in pod
local containers
containers=$(kubectl get pod "$existing_pod" -o jsonpath='{.spec.containers[*].name}' 2>/dev/null)
local found=0
for c in $containers; do
if [[ "$c" == "$container" ]]; then
found=1
break
fi
done
if [[ $found -eq 0 ]]; then
echo "Error: Container '$container' not found in pod '$existing_pod'" >&2
echo "Available containers:" >&2
for c in $containers; do
echo " - $c" >&2
done
exit 1
fi
# Write/update config file
{
echo "# Auto-generated by kns"
if [[ -n "$existing_context" ]]; then
echo "KNS_CONTEXT=\"$existing_context\""
fi
if [[ -n "$existing_namespace" ]]; then
echo "KNS_NAMESPACE=\"$existing_namespace\""
fi
if [[ -n "$existing_pod" ]]; then
echo "KNS_POD=\"$existing_pod\""
fi
echo "KNS_CONTAINER=\"$container\""
} > "$file"
echo "Set current container: $container"
}
# Get containers of current pod
cmd_get_containers() {
# Source all files directly (not in subshell)
unset KNS_CONTEXT KNS_NAMESPACE KNS_POD KNS_CONTAINER
# Collect all .kns.conf files from current directory up to root
local files=()
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
files+=("$HOME/$KNS_LOCAL_FILE")
fi
if [[ ${#files[@]} -eq 0 ]]; then
echo "Error: No .kns.conf file found in current or parent directories" >&2
exit 1
fi
# Source files in reverse order (parent/home first, then current)
local i
for ((i=${#files[@]}-1; i>=0; i--)); do
if [[ -f "${files[i]}" ]]; then
source "${files[i]}" 2>/dev/null || true
fi
done
if [[ -z "${KNS_POD:-}" ]]; then
echo "Error: Current pod not set. Use 'kns sp <pod-name>' to set it." >&2
exit 1
fi
# Auto-switch context if needed
auto_switch_context
# Get containers from pod
local containers
containers=$(kubectl get pod "$KNS_POD" -o jsonpath='{.spec.containers[*].name}' 2>/dev/null)
if [[ -z "$containers" ]]; then
echo "Error: Could not retrieve containers for pod '$KNS_POD'" >&2
exit 1
fi
echo "Pod: $KNS_POD"
echo "Containers:"
for container in $containers; do
if [[ "$container" == "${KNS_CONTAINER:-}" ]]; then
echo " - $container (current)"
else
echo " - $container"
fi
done
}
# Get current pod and container from config
get_current_pod_container() {
# Source all files directly (not in subshell)
# Clear any existing values first
unset KNS_CONTEXT KNS_NAMESPACE KNS_POD KNS_CONTAINER
# Collect all .kns.conf files from current directory up to root
local files=()
local dir="$PWD"
# First, collect files from current directory up to root
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$KNS_LOCAL_FILE" ]]; then
files+=("$dir/$KNS_LOCAL_FILE")
fi
dir=$(dirname "$dir")
done
# Add home directory file if it exists
if [[ -f "$HOME/$KNS_LOCAL_FILE" ]]; then
files+=("$HOME/$KNS_LOCAL_FILE")
fi
# If no files found, return error
if [[ ${#files[@]} -eq 0 ]]; then
return 1
fi
# Source files in reverse order (parent/home first, then current)
# This way current directory values override parent values
local i
for ((i=${#files[@]}-1; i>=0; i--)); do
if [[ -f "${files[i]}" ]]; then
source "${files[i]}" 2>/dev/null || true
fi
done
# Check if pod is set
if [[ -z "${KNS_POD:-}" ]]; then
return 1
fi
echo "${KNS_POD}:${KNS_CONTAINER:-}"
}
# Execute command in pod/container
cmd_exec() {
local pod_container
if ! pod_container=$(get_current_pod_container); then
echo "Error: Current pod not set. Use 'kns sp <pod-name>' to set it." >&2
exit 1
fi
IFS=':' read -r pod container <<< "$pod_container"
# Validate pod name
if [[ -z "$pod" ]]; then
echo "Error: Pod name is empty" >&2
exit 1
fi
# Auto-switch context if needed
auto_switch_context
# Get namespace from context if available
local namespace=""
namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}' 2>/dev/null || echo "")
# Execute with remaining arguments
if [[ $# -eq 0 ]]; then
echo "Usage: kns exec <command> [args...]" >&2
exit 1
fi
# Verify pod exists
local get_pod_cmd="kubectl get pod"
if [[ -n "$namespace" ]]; then
get_pod_cmd="$get_pod_cmd -n $namespace"
fi
if ! $get_pod_cmd "$pod" >/dev/null 2>&1; then
echo "Error: Pod '$pod' not found" >&2
if [[ -n "$namespace" ]]; then
echo " (checked in namespace: $namespace)" >&2
fi
exit 1
fi
# Execute the command with explicit namespace if available
local exec_result=0
if [[ -n "$namespace" ]]; then
if [[ -n "$container" ]]; then
kubectl exec -n "$namespace" -c "$container" "$pod" -- "$@" || exec_result=$?
else
kubectl exec -n "$namespace" "$pod" -- "$@" || exec_result=$?
fi
else
if [[ -n "$container" ]]; then
kubectl exec -c "$container" "$pod" -- "$@" || exec_result=$?
else
kubectl exec "$pod" -- "$@" || exec_result=$?
fi
fi
# If command failed with "not found" error, provide helpful message
if [[ $exec_result -eq 127 ]]; then
echo "" >&2
echo "Note: Command '${1:-}' not found in container PATH." >&2
echo "This container may be minimal/distroless. Try:" >&2
echo " - Using full path to the executable" >&2
echo " - Checking what's available: kubectl exec $pod -- ls /bin /usr/bin" >&2
echo " - Using 'kns sh' if a shell is available" >&2
fi
exit $exec_result
}
# Copy files to/from pod
cmd_copy() {
if [[ $# -lt 2 ]]; then
echo "Usage: kns cp <source> <destination>" >&2
echo "" >&2
echo "Examples:" >&2
echo " kns cp local.txt pod:/path/to/file # Copy to pod" >&2
echo " kns cp pod:/path/to/file local.txt # Copy from pod" >&2
echo " kns cp local.txt pod:/path/ # Copy to pod directory" >&2
exit 1
fi
local source="$1"
local dest="$2"
local pod_container
if ! pod_container=$(get_current_pod_container); then
echo "Error: Current pod not set. Use 'kns sp <pod-name>' to set it." >&2
exit 1
fi
IFS=':' read -r pod container <<< "$pod_container"
# Auto-switch context if needed
auto_switch_context
# Determine direction: if source starts with "pod:", it's pod->local, else local->pod
local final_source=""
local final_dest=""
if [[ "$source" == pod:* ]]; then
# pod->local: pod:/path -> local
local pod_path="${source#pod:}"
if [[ -n "$container" ]]; then
final_source="${pod}:${container}:${pod_path}"
else
final_source="${pod}:${pod_path}"
fi
final_dest="$dest"
elif [[ "$dest" == pod:* ]]; then
# local->pod: local -> pod:/path
local pod_path="${dest#pod:}"
final_source="$source"
if [[ -n "$container" ]]; then
final_dest="${pod}:${container}:${pod_path}"
else
final_dest="${pod}:${pod_path}"
fi
else
echo "Error: One of source or destination must use 'pod:' prefix" >&2
echo "Example: kns cp local.txt pod:/tmp/file.txt" >&2
exit 1
fi
kubectl cp "$final_source" "$final_dest"
}
# Shell into pod/container
cmd_shell() {
local pod_container
if ! pod_container=$(get_current_pod_container); then
echo "Error: Current pod not set. Use 'kns sp <pod-name>' to set it." >&2
exit 1
fi
IFS=':' read -r pod container <<< "$pod_container"
# Validate pod name
if [[ -z "$pod" ]]; then
echo "Error: Pod name is empty" >&2
exit 1
fi
# Auto-switch context if needed
auto_switch_context
# Get namespace from context if available
local namespace=""
namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}' 2>/dev/null || echo "")
# Verify pod exists
local get_pod_cmd="kubectl get pod"
if [[ -n "$namespace" ]]; then
get_pod_cmd="$get_pod_cmd -n $namespace"
fi
if ! $get_pod_cmd "$pod" >/dev/null 2>&1; then
echo "Error: Pod '$pod' not found" >&2
if [[ -n "$namespace" ]]; then
echo " (checked in namespace: $namespace)" >&2
fi
exit 1
fi
# Try common shells in order - test by trying to exec them
local shell=""
local test_cmd=""
if [[ -n "$namespace" ]]; then
if [[ -n "$container" ]]; then
test_cmd="kubectl exec -n $namespace -c $container $pod"
else
test_cmd="kubectl exec -n $namespace $pod"
fi
else
if [[ -n "$container" ]]; then
test_cmd="kubectl exec -c $container $pod"
else
test_cmd="kubectl exec $pod"
fi
fi
for sh in sh bash zsh; do
# Try to execute the shell with a simple command to see if it exists
if $test_cmd -- "$sh" -c "exit 0" >/dev/null 2>&1; then
shell="$sh"
break
fi
done
if [[ -z "$shell" ]]; then
echo "Error: No shell found in container. This container appears to be distroless or minimal." >&2
echo "" >&2
echo "Available options:" >&2
echo " 1. Use 'kns exec <command>' to run specific commands" >&2
echo " 2. Check what executables are available in the container" >&2
echo " 3. Use kubectl exec directly with the full path to an executable" >&2
exit 1
fi
# Execute shell interactively
if [[ -n "$namespace" ]]; then
if [[ -n "$container" ]]; then
kubectl exec -it -n "$namespace" -c "$container" "$pod" -- "$shell"
else
kubectl exec -it -n "$namespace" "$pod" -- "$shell"
fi
else
if [[ -n "$container" ]]; then
kubectl exec -it -c "$container" "$pod" -- "$shell"
else
kubectl exec -it "$pod" -- "$shell"
fi
fi
}
# Show help
show_help() {
cat <<EOF
kns - Kubernetes Namespace/Context Switcher
Automatically switches kubectl context and namespace based on your current directory.
Similar to how asdf uses .tool-versions files, kns uses .kns.conf files.
USAGE:
kns <command> [arguments]
CONTEXT MANAGEMENT:
set <context> [namespace] Set context for current directory
current Show current context/namespace and source file
use <context> [namespace] Manually switch context (temporarily overrides .kns.conf)
list List all available kubectl contexts
link <context> [namespace] Alias for 'set'
unlink Remove context from current directory
KUBECTL SHORTCUTS:
gp kubectl get pods
gs kubectl get services
gd kubectl get deployments
ns kubectl get namespaces
POD & CONTAINER MANAGEMENT:
sp <pod-name> Set current pod for this directory
sc <container-name> Set current container (requires pod to be set first)
gc List containers of current pod
exec <command> [args...] Execute command in current pod/container
cp <source> <dest> Copy files to/from pod (use 'pod:' prefix for pod paths)
sh Interactive shell into current pod/container
help, -h, --help Show this help message
EXAMPLES:
# Context management
kns set production-cluster production
kns current # Shows context and source file
kns use staging-cluster staging # Temporary override
kns list # List all contexts
kns unlink # Remove .kns.conf
# Quick kubectl commands
kns gp # Get pods
kns gs # Get services
# Pod and container management
kns sp my-pod-123 # Set current pod
kns sc my-container # Set current container
kns gc # List containers in current pod
kns exec ls -la /tmp # Execute command
kns cp local.txt pod:/tmp/file.txt # Copy to pod
kns cp pod:/tmp/file.txt local.txt # Copy from pod
kns sh # Interactive shell
CONFIGURATION:
Configuration is stored in .kns.conf files in your project directories.
The tool searches for .kns.conf in the current directory and parent directories
(similar to asdf's .tool-versions lookup).
The .kns.conf file can contain:
- KNS_CONTEXT: Kubernetes context name
- KNS_NAMESPACE: Kubernetes namespace
- KNS_POD: Current pod name
- KNS_CONTAINER: Current container name (optional)
The tool automatically switches context when you cd into a directory.
Pod and container settings are preserved when updating context.
For file copy operations, use 'pod:' prefix to indicate pod paths:
- kns cp local.txt pod:/tmp/file.txt (copy to pod)
- kns cp pod:/tmp/file.txt local.txt (copy from pod)
EOF
}
main "$@"