Repository navigation
Expand file tree
/
Copy pathfubectl.source
More file actions
executable file
·762 lines (701 loc) · 29.2 KB
/
Copy pathfubectl.source
File metadata and controls
executable file
·762 lines (701 loc) · 29.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
#fix ZSH - perform field splitting - http://zsh.sourceforge.net/Doc/Release/Options.html
# shellcheck disable=SC2148
if [ -n "$ZSH_VERSION" ]
then
setopt SH_WORD_SPLIT
fi
function completion_wrapper() {
local RARG='-a'
[[ -n "$ZSH_VERSION" ]] && RARG='-A'
# ex: completion_wrapper kgns 'get ns'
[[ "$#" == 2 ]] || return 1
local alias_name="$1"
local alias_args="$2"
eval "local alias_arg_words; alias_arg_words=($alias_args)" 2>/dev/null || return
read $RARG alias_arg_words <<< "$alias_args"
local compl_func="__start_kubectl"
local wrapper_name="alias_completion::${alias_name}"
eval "
function ${wrapper_name}() {
(( COMP_CWORD += ${#alias_arg_words[@]} ))
COMP_WORDS=(kubectl $alias_args \${COMP_WORDS[@]:1})
(( COMP_POINT -= \${#COMP_LINE} ))
COMP_LINE=\${COMP_LINE/$alias_name/kubectl $alias_args}
(( COMP_POINT += \${#COMP_LINE} ))
$compl_func
}
"
eval "complete -o default -F $wrapper_name $alias_name"
}
# helper functions
alias _inline_fzf="fzf --multi --ansi -i -1 --height=50% --reverse -0 --header-lines=1 --inline-info --border"
alias _inline_fzf_nh="fzf --multi --ansi -i -1 --height=50% --reverse -0 --inline-info --border"
_k8s_export() {
yq e 'del(.metadata.resourceVersion)' -\
| yq e 'del(.metadata.uid)' -\
| yq e 'del(.metadata.annotations."cni.projectcalico.org/podIP")' -\
| yq e 'del(.metadata.annotations.checksum/config)' -\
| yq e 'del(.metadata.creationTimestamp)' -\
| yq e 'del(.metadata.ownerReferences)' -\
| yq e 'del(.metadata.generateName)' -\
| yq e 'del(.metadata.selfLink)' -\
| yq e 'del(.status)' -\
| yq e 'del(.spec.nodeName) | del(.metadata.managedFields) | del(.specs.schedulerName)' -\
| yq e 'del(.spec.containers[]|.volumeMounts[]|select(.mountPath == "/var/run/secrets/kubernetes.io/serviceaccount"))' -\
| yq e 'del(.spec.containers[]|.terminationMessagePath)' -\
| yq e 'del(.spec.containers[]|.terminationMessagePolicy)' -\
| yq e 'del(.spec.containers[]|.imagePullPolicy)' -\
| yq e 'del(.spec.containers[]|.dnsPolicy)' -\
| yq e 'del(.spec.containers[]|.dnsPolicy)' -\
| yq e 'del(.spec.containers[]|.enableServiceLinks)' -
}
#| yq e 'del(.metadata.annotations."kubectl.kubernetes.io/last-applied-configuration")' -\
# [kexp] as former `--export` field removes unwanted metadata - usage: kexp RESOURCE
function kexp(){
typeset -l kind
local kind="$1"
[ -z "$kind" ] && printf "kexp: missing argument.\nUsage: kexp RESOURCE\n" && return 255
local cmd="kubectl get $* -oyaml"
if [ -z "$2" ]; then
cmd="kget $*"
fi
if [[ "${kind}" =~ pod? ]]; then
local TMP_RES
TMP_RES=$(mktemp -t k8s-res-XXXX)
if [ -n "$2" ]; then
kubectl get "$@" -oyaml >$TMP_RES
else
kubectl get po >$TMP_RES
fi
local k8s_sa
k8s_sa=$(yq e '(.spec.containers[] | .volumeMounts[] | select(.mountPath == "/var/run/secrets/kubernetes.io/serviceaccount")|.name )' $TMP_RES|uniq)
export k8s_sa
cat $TMP_RES|_k8s_export \
| yq e 'del(.spec.volumes[]|select(.name == env(k8s_sa)))' -
rm -f $TMP_RES
else
$cmd |_k8s_export
fi
}
completion_wrapper kexp 'get'
function _isClusterSpaceObject() {
# caller is responsible for assuring non-empty "$1"
obj="$1"
kubectl api-resources --namespaced=false \
| awk '(apiidx){print substr($0, 0, apiidx),substr($0, kindidx) } (!apiidx){ apiidx=index($0, " APIVERSION");kindidx=index($0, " KIND")}' \
| grep -iq "\<${obj}\>"
}
# [k] like g for git but 233% as effective!
alias k="kubectl"; complete -o default -F __start_kubectl k
alias kg='k get'; completion_wrapper kg 'get'
alias kgns='k get ns'; completion_wrapper kgns 'get ns'
alias kl='k logs'; completion_wrapper kl 'logs'
alias kaf='k apply -f'; completion_wrapper kaf 'apply -f'
alias kdelf='k delete -f'; completion_wrapper kdelf 'delete -f'
alias kdel-force='k delete --grace-period=0 --force'; completion_wrapper kdelf 'delete'
alias kd='k describe'; completion_wrapper kd 'describe'
alias kdp='k describe po'; completion_wrapper kdp 'describe po'
alias kds='k describe svc'; completion_wrapper kds 'describe svc'
alias kgp='k get po'; completion_wrapper kgp 'get po'
alias kgpf='k get po -ogo-template="{{range .items}}{{if eq .status.phase \"Failed\"}}{{.metadata.name}}{{\"\n\"}}{{end}}{{end}}"'
function kgpy() { k get po -oyaml "$@"|_k8s_export; }; completion_wrapper kgpy 'get po'
alias kgpw='k get po -owide'; completion_wrapper kgpw 'get po -owide'
alias kgpa='kubectl get pods -A --field-selector=metadata.namespace!=kube-system -ojsonpath='"'"'{range .items[*]}{@.metadata.name}{" "}{@.metadata.namespace}{" "}{@.status.phase}{" "}{@.status.hostIP}{" "}{@.spec.nodeName}{"\n"}{end}'"'"'|column -t'
alias kgpaw='kubectl get pods -A -owide --field-selector=metadata.namespace!=kube-system -ojsonpath='"'"'{range .items[*]}{@.metadata.name}{" "}{@.metadata.namespace}{" "}{@.status.phase}{" "}{@.status.hostIP}{" "}{@.spec.nodeName}{"\n"}{end}'"'"'|column -t'
alias kgpawk='kubectl get pods -A -owide -ojsonpath='"'"'{range .items[*]}{@.metadata.name}{" "}{@.metadata.namespace}{" "}{@.status.phase}{" "}{@.status.hostIP}{" "}{@.spec.nodeName}{"\n"}{end}'"'"'|column -t'
alias kgs='k get svc'; completion_wrapper kgs 'get svc'
function kgsy() { k get svc -oyaml "$@"|_k8s_export; }; completion_wrapper kgsy 'get svc'
alias kgd='k get deploy'; completion_wrapper kgd 'get deploy'
function kgdy() { k get deploy -oyaml "$@"|_k8s_export; }; completion_wrapper kgdy 'get deploy'
alias kgds='k get ds'; completion_wrapper kgds 'get ds'
function kgdsy() { k get ds -oyaml "$@"|_k8s_export; }; completion_wrapper kgdsy 'get ds'
alias kge='k get ev'; completion_wrapper kge 'get ev'
alias kgew='k get ev -w'; completion_wrapper kgew 'get ev -w'
alias kgewa='k get ev -w -A'
alias kgsec='k get secret'; completion_wrapper kgsec 'get secret'
function kgsecy() { k get secret -oyaml "$@"|_k8s_export; }; completion_wrapper kgsec 'get secret'
alias kgsa='k get sa'; completion_wrapper kgsa 'get sa'
alias kexec='k exec'; completion_wrapper kexec 'exec'
alias kgcm='k get cm'; completion_wrapper kgcm 'get cm'
function kgcmy() { k get cm -oyaml "$@"|_k8s_export; }; completion_wrapper kgcm 'get cm'
alias kgj='k get jobs'; completion_wrapper kgj 'get jobs'
alias kgn='k get no'; completion_wrapper kgn 'get no'
alias kgnw='k get no -owide'; completion_wrapper kgnw 'get no'
alias ktn='k top no --use-protocol-buffers'; completion_wrapper ktn 'top no'
alias ktp='k top po --use-protocol-buffers'; completion_wrapper ktp 'top po'
#source <(kubectl completion bash | sed s/kubectl/k/g)
alias krun='kubectl run --restart=Never'; completion_wrapper krun 'run'
function krun-ci() {
# local img="${1:-us.gcr.io/i-dss-infrastructure-prod/base-slim:latest}"
local img
local cmd=/bin/sh
[[ -n "$1" ]] && img=$1 ||\
img=$(printf "DOCKER_IMAGE
us.gcr.io/i-dss-infrastructure-prod/base-slim
us.gcr.io/i-dss-infrastructure-prod/base-python:3-slim
us.gcr.io/i-dss-infrastructure-prod/base-python:3-build
us.gcr.io/i-dss-infrastructure-prod/ci-tools:v0.3.0
msgongora/k8s-test
hashicorp/terraform
gcr.io/cloud-builders/gcloud
gcr.io/cloud-builders/kubectl
gcr.io/cloud-builders/bazel
gcr.io/kaniko-project/executor:debug"|awk '{print $1}'|_inline_fzf)
[[ -n "$2" ]] && cmd=$2
echo "$img"|grep -q kaniko && cmd=/busybox/sh
echo "$img"|grep -Eq "gcloud|kubectl|bazel|builders/(git|go)$" && cmd=/bin/bash
[[ -n "$img" ]] \
&& krun -i --rm --tty --restart=Never --image-pull-policy=IfNotPresent shell-$RANDOM --image="$img" --command $cmd --overrides '{"spec":{"nodeSelector": {"node_pool": "intensive-pool"},"tolerations": [{"effect": "NoSchedule","key": "high-perform","operator": "Equal","value":"true"}],"serviceAccount":"devops-sa"}}'
}
# [kfinalizer] Remove finalizer from a namespace
function kfinalizer() {
ns=$(kubectl get ns| _inline_fzf|awk '{print $1}')
kubectl get ns $ns -ojson|grep -v '"kubernetes"'|\
kubectl replace --raw "/api/v1/namespaces/$ns/finalize" -f -
}
# [kcontainers] List all pods and their containers
alias kcontainers='kubectl get po -o=custom-columns="NAME:.metadata.name,CONTAINERS:.spec.containers[*].name"'; completion_wrapper kcontainers 'get po'
# [kges] get sorted events
function kges() {
{
echo $'TIME\tNAMESPACE\tTYPE\tREASON\tOBJECT\tSOURCE\tMESSAGE';
kubectl get ev -ojson "$@" \
| jq -r '.items | map(. + {t: (.eventTime//.lastTimestamp)}) | sort_by(.t)[] | [.t, .metadata.namespace, .type, .reason, .involvedObject.kind + "/" + .involvedObject.name, .source.component + "/" + (.source.host//"-"), .message] | @tsv';
} \
| column -s $'\t' -t
}
# [kw] kw get po,svc,md
alias kw="watch kubectl get"; completion_wrapper kw get
alias kw1="watch -n1 kubectl get"; completion_wrapper kw1 get
# [ka] get all pods in namespace
alias ka="kubectl get pods"
# [kall] get all pods in cluster
alias kall="kubectl get pods --all-namespaces"
# [kwa] watch all pods in the current namespace
alias kwa="watch kubectl get pods"; completion_wrapper kwa 'get po'
# [kwall] watch all pods in cluster
alias kwall="watch kubectl get pods --all-namespaces"
# TODO use "open" instead of "xdg-open" on a mac - also redirect xdg-open std{out,err} to /dev/null
# [kp] open kubernetes dashboard with proxy
#alias kp="xdg-open 'http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/' & kubectl proxy"
# [kwatch] watch resource
function kwatch() {
local kind="$1"
[ -z "$kind" ] && printf "kwatch: missing argument.\nUsage: kwatch RESOURCE\n" && return 255
if _isClusterSpaceObject "$kind" ; then
(printf "NAME\n";kubectl get "${kind}" --sort-by=.metadata.name \
-ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}') |\
_inline_fzf | xargs watch kubectl get "${kind}"
else
(printf "NAMESPACE NAME\n";kubectl get "${kind}" -A \
--field-selector=metadata.namespace!=kube-system -ojsonpath='
{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}') |\
column -t| _inline_fzf | xargs watch kubectl get "${kind}" -n
fi
}
# [kcmd] create a pod and execute a cmd/image (default bash/ubuntu) usage: "kcmd cmd" or "kcmd cmd image"
function kcmd() {
local cmd="$1"
local name=shell-$RANDOM
local image="msgongora/k8s-test:latest"
if [ -n "$2" ]; then
image="$2"
fi
local ns="$(kubectl get ns | _inline_fzf | awk '{print $1}')"
if [ -n "$cmd" ]; then
kubectl run $name --restart=Never --namespace $ns --rm -i --tty --image ${image} -- /bin/sh -c "${cmd}"
else
kubectl run $name --restart=Never --namespace $ns --rm -i --tty --image ${image} -- sh
fi
}
# [kcmd-root] create a pod and execute a cmd/image (default bash/ubuntu) usage: "kcmd cmd" or "kcmd cmd image"
kcmd-root() {
local name=shell-$RANDOM
local node_hostname=$( (printf "NODE\n";kubectl get node --label-columns=kubernetes.io/hostname -ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}') |_inline_fzf)
local image="msgongora/k8s-test:latest"
if [ -n "$1" ]; then
image="$1"
fi
local ns="$( (printf "NAMESPACE\n"; kubectl get ns -ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}')| _inline_fzf)"
local overrides='
{
"spec": {
"hostPID": true,
"hostNetwork": true,
"tolerations": [
{
"operator": "Exists",
"effect": "NoSchedule"
},
{
"operator": "Exists",
"effect": "NoExecute"
}
],
"containers": [
{
"name": "'$name'",
"image": "'$image'",
"command": [
"/bin/sh"
],
"stdin": true,
"stdinOnce": true,
"tty": true,
"securityContext": {
"privileged": true
}
}
],
"nodeSelector": {
"kubernetes.io/hostname": "'$node_hostname'"
}
}
}
'
kubectl run $name --restart=Never -n $ns --rm -it --image $image --overrides="${overrides}"
}
# [kube_ctx_name] get the current context
kube_ctx_name() {
kubectl config current-context
}
# [kube_ctx_namespace] get current namespace
kube_ctx_namespace() {
local default_ns="$(kubectl config view --minify|grep namespace: |sed 's/namespace: //g'|tr -d ' ')"
default_ns="${default_ns:-default}"
echo "$default_ns"
}
# [kget] get a resource by its YAML
kget() {
# if [ $# -gt 1 ]; then
# kubectl get $@ -oyaml
# return 0
# fi
local kind="$1"
[ -z "$kind" ] && printf "kget: missing argument.\nUsage: kget RESOURCE\n" && return 255
if _isClusterSpaceObject "$kind" ; then
(printf "NAME\n";kubectl get "$kind" --sort-by=.metadata.name -ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}')| _inline_fzf | xargs kubectl get -o yaml "$kind"
else
(printf "NAMESPACE NAME\n";kubectl get "$kind" -A --sort-by=.metadata.namespace --field-selector=metadata.namespace!=kube-system -ojsonpath='{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}') |column -t| _inline_fzf | xargs kubectl get -o yaml "$kind" -n
fi
}
completion_wrapper kget 'get'
# [ked] edit a resource by its YAML
ked() {
local kind="$1"
if [ -z "$kind" ]; then
echo "ked requires resource-type (pod,deployment,...) as argument."
return 255
fi
local arg_pair
if [ -z "$2" ]; then
if _isClusterSpaceObject "$kind" ; then
arg_pair=$( (printf "NAME\n"; kubectl get "$kind" --sort-by=.metadata.name -ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}')| _inline_fzf )
else
arg_pair="-n $( (printf "NAMESPACE NAME\n";kubectl get "$kind" -A --field-selector=metadata.namespace!=kube-system -ojsonpath='{range .items[?(@.status.phase=="Running")]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}')|column -t| _inline_fzf )"
fi
kubectl edit $kind $arg_pair
else
kubectl edit $*
fi
# kubectl get $kind $arg_pair -ojsonpath='{.metadata.labels}'|grep -Po "map\[\K.*(?=\])"|tr ':' '='|tr ' ' '\n'
}
completion_wrapper ked 'edit'
# [kdes] describe resource
kdes() {
local kind="$1"
[ -z "$kind" ] && printf "kdes: missing argument.\nUsage: kdes RESOURCE\n" && return 255
if [ -z "$2" ]; then
if _isClusterSpaceObject "$kind" ; then
(printf "NAME\n"; kubectl get "$kind" --sort-by=.metadata.name \
-ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}')| _inline_fzf |\
xargs kubectl describe "$kind"
else
(printf "NAMESPACE NAME STATUS\n";kubectl get "$kind" -A \
--field-selector=metadata.namespace!=kube-system \
-ojsonpath='{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{" "}{@.status.phase}{"\n"}{end}')|\
column -t| _inline_fzf | xargs kubectl describe "$kind" -n
fi
else
kubectl describe $*
fi
}
completion_wrapper kdes 'describe'
# [kdel] delete resource
kdel() {
local kind="$1"
[ -z "$kind" ] && printf "kdel: missing argument.\nUsage: kdel RESOURCE\n" && return 255
if [[ -z "$2" ]]; then
if _isClusterSpaceObject "$kind" ; then
(printf "NAME\n";kubectl get "$kind" --sort-by=.metadata.name \
-ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}')| _inline_fzf |\
xargs -p kubectl delete "$kind"
elif [ "$kind" = "evicted" ]; then
kubectl get pods -A -o \
go-template='{{range .items}}{{if eq .status.phase "Failed"}}{{if eq .status.reason "Evicted"}}kubectl delete pod -n {{.metadata.namespace}} {{.metadata.name}}{{"\n"}}{{end}}{{end}}{{end}}'|\
xargs -I/ sh -c "/"
else
(printf "NAMESPACE NAME\n";kubectl get "$kind" -A \
--field-selector=metadata.namespace!=kube-system \
-ojsonpath='{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}')\
|column -t| _inline_fzf | xargs -r -p kubectl delete "$kind" -n
# --sort-by=.metadata.creationTimestamp
fi
else
kubectl delete $kind $2
fi
}
completion_wrapper kdel 'delete'
# [klog] fetch log from container
_klog_usage() {
cat <<'EOF'
Usage: klog [LINECOUNT] [options]
First argument is interpreted as LINECOUNT if it matches integer syntax.
Additional `options` are passed on (see `kubectl logs --help` for details).
EOF
}
klog() {
[ "$1" = "--help" ] && _klog_usage && return
local line_count=10
if [[ $1 =~ ^[-]{0,1}[0-9]+$ ]]; then
line_count="$1"
shift
fi
local arg_pair=$(kubectl get po --all-namespaces | _inline_fzf | awk '{print $1, $2}')
[ -z "$arg_pair" ] && printf "klog: no pods found. no logs can be shown.\n" && return
local containers_out
containers_out=$(kubectl get po \
-o=jsonpath='{.spec.containers[*].name} {.spec.initContainers[*].name}' \
-n $arg_pair | sed 's/ $//')
local container_choosen=$(echo "$containers_out" | tr ' ' "\n" | _inline_fzf_nh)
kubectl logs -n ${arg_pair} -c "${container_choosen}" --tail="${line_count}" "$@"
}
completion_wrapper klog 'logs'
# [kex] execute command in container
kex() {
#[ -z "$1" ] && printf "kex: missing argument(s).\nUsage: kex COMMAND [arguments]\n" && return 255
local args="$*"
[[ -z "$1" ]] && args="bash"
local arg_pair
arg_pair=$( (printf "NAMESPACE NAME\n"; kubectl get po -A \
--field-selector=metadata.namespace!=kube-system -ojsonpath='
{range .items[?(@.status.phase=="Running")]}
{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}
{end}') | column -t | _inline_fzf)
[ -z "$arg_pair" ] && printf "kex: no pods found. no execution.\n" && return
local containers_out
containers_out=$(echo "$arg_pair" | xargs kubectl get po \
-o=jsonpath='{.spec.containers[*].name}' -n)
local container_choosen
container_choosen=$(echo "$containers_out" | tr ' ' "\n" | _inline_fzf_nh)
kubectl exec -it -n ${arg_pair} -c "${container_choosen}" -- "$args"
}
# [kfor] port-forward a container port to your local machine
kfor() {
local arg="$1"
local port="$2"
# [ -z "$arg" ] && printf "kfor: missing argument.\nUsage: kfor PORT_TO_FORWARD\n" && return 255
local arg_pair
FILTER='{{range .spec.containers}}
{{range .ports}}
{{if eq .protocol "TCP"}}
{{$ns}}{{" "}}{{$name}}{{" "}}{{.containerPort}}{{"\n"}}
{{end}}
{{end}}
{{end}}{{end}}'
: "${arg:=po}"
if echo $arg | grep -qE '^[0-9]+$'; then
port=$arg
arg=po
elif [ "$arg" = "svc" ]; then
arg=svc
FILTER=' {{range .spec.ports}}
{{if eq .protocol "TCP"}}
{{$ns}}{{" "}}{{$name}}{{" "}}{{.port}}{{"\n"}}
{{end}}
{{end}}{{end}}'
elif [ "$arg" = "deploy" ]; then
FILTER='{{range .spec.template.spec.containers}}
{{range .ports}}
{{if eq .protocol "TCP"}}
{{$ns}}{{" "}}{{$name}}{{" "}}{{.containerPort}}{{"\n"}}
{{end}}
{{end}}
{{end}}{{end}}'
fi
# shellcheck disable=SC2016
arg_pair=$( (printf "NAMESPACE NAME PORT\n"; kubectl get $arg -A \
--field-selector=metadata.namespace!=kube-system \
-o go-template="{{range .items}}
{{\$name := .metadata.name}}
{{\$ns := .metadata.namespace}}
$FILTER") | column -t | _inline_fzf)
[ -z "$arg_pair" ] && \
printf "kfor: no pods found. no forwarding.\n" && return 1
if [ -n "$port" ]; then
arg_pair=$( echo $arg_pair |\
awk -v port=$port -v res=$arg '{print $1, res"/"$2, port":"$3}')
else
arg_pair=$( echo $arg_pair |\
awk -v res=$arg '{print $1, res"/"$2, $3}')
fi
kubectl port-forward -n $arg_pair
}
# [klabels] get labels
klabels() {
local kind="$1"
local arg_pair
if [ -z "$kind" ]; then
arg_pair=$( (printf "NAMESPACE NAME\n";kubectl get po -A -ojsonpath='
{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}') |\
column -t | _inline_fzf)
arg_pair="-n $arg_pair"
kind=po
else
if _isClusterSpaceObject "$kind" ; then
arg_pair=$( (printf "NAME\n"; kubectl get "$kind" --sort-by=.metadata.name \
-ojsonpath='{range .items[*]}{@.metadata.name}{"\n"}{end}') | _inline_fzf)
else
arg_pair=$( (printf "NAMESPACE NAME STATUS\n";kubectl get "$kind" -A \
-ojsonpath='{range .items[*]}
{@.metadata.namespace}{" "}{@.metadata.name}{" "}{@.status.phase}{"\n"}
{end}') | column -t| _inline_fzf)
arg_pair="-n $arg_pair"
fi
fi
# kubectl get $kind $arg_pair -ojsonpath='{.metadata.labels}'|grep -Po "map\[\K.*(?=\])"|tr ':' '='|tr ' ' '\n'
kubectl get $kind $arg_pair \
-ojsonpath='{.metadata.labels}'|grep -Po "{\K.*(?=})"| tr ':' '=' |tr -d \"|tr ',' '\n'
}
# [kstern] start to get pod events using stern
kstern() {
local arg_pair
arg_pair=$( (printf "NAMESPACE NAME\n";kubectl get po -A -ojsonpath='
{range .items[*]}{@.metadata.namespace}{" "}{@.metadata.name}{"\n"}{end}
') | column -t | _inline_fzf)
ns=$(echo "$arg_pair"|awk '{print $1}')
#echo kubectl get po -n $arg_pair -ojsonpath='{.metadata.labels}'
local label=$(kubectl get po -n $arg_pair -ojsonpath='{.metadata.labels}'|\
grep -Po "{\K.*(?=})"| tr ':' '=' |tr -d \"|tr ',' '\n'|_inline_fzf_nh)
echo -n "Running stern with '-l $label -n $ns'"
if [ -z "$1" ]; then
echo
stern -l $label -n $ns
else
echo " $*"
stern -l $label -n $ns $*
fi
}
# [ksearch] search for string in resources
ksearch() {
local search_query="$1"
[ -z "$search_query" ] && printf "ksearch: missing argument.\nUsage: ksearch SEARCH_QUERY\n" \
&& return 255
for ns in $(kubectl get --export -o=json ns | jq -r '.items[] | .metadata.name'); do
kubectl --namespace="${ns}" get --export -o=json \
deployment,ingress,daemonset,secrets,configmap,service,serviceaccount,statefulsets,pod,endpoints,customresourcedefinition,events,networkpolicies,persistentvolumeclaims,persistentvolumes,replicasets,replicationcontrollers,statefulsets,storageclasses | \
jq '.items[]' -c | \
grep "$search_query" | \
jq -r '. | [.kind, .metadata.name] | @tsv' | \
awk -v prefix="$ns" '{print "kubectl get -n " prefix " " $0}'
done
}
# [kcl] context list
alias kcl='kubectl config get-contexts'
# [kcdel] context delete and its dependencies
kcdel() {
export _ctx=$((printf "CONTEXT NAME\n"; kubectl config get-contexts -oname)|_inline_fzf)
export _cluster=$(yq e '.contexts[]|select(.name == env(_ctx))|.context.cluster' \
~/.kube/config)
local more_ctx=$(yq e '.contexts[]|select(.context.cluster == env(_cluster)).name' \
~/.kube/config|wc -l)
if [ $more_ctx -eq 1 ]; then
kubectl config delete-cluster $_cluster
kubectl config unset users.$(yq e '.contexts[]|select(.name == env(_ctx))|.context.user' \
~/.kube/config)
kubectl config delete-context "${_ctx}"
fi
unset _ctx _cluster
}
# [kcs] context set
kcs() {
local context="$(kubectl config get-contexts --no-headers -oname| _inline_fzf | cut -b4- | \
awk '{print $1}')"
kubectl config set current-context "${context}"
}
# [kns] context set default namespace
kns() {
local ns="$1"
if [ -z "$ns" ]; then
ns="$(kubectl get ns | _inline_fzf | awk '{print $1}')"
fi
[ -z "$ns" ] && printf "kcns: no namespace selected/found.\nUsage: kcns [NAMESPACE]\n" \
&& return
kubectl config set-context "$(kubectl config current-context)" --namespace="${ns}"
}
completion_wrapper kns 'get ns'
# [kwns] watch pods in a namespace
kwns() {
local ns=$(kubectl get ns | _inline_fzf | awk '{print $1}')
[ -z "$ns" ] && printf "kcns: no namespace selected/found.\nUsage: kwns\n" && return
watch kubectl get pod -n "$ns"
}
# [ktree] prints a tree of k8s objects (kubectl tree plugin needs to be installed)
# ktree() {
# local kind="$1"
# if [ -z "$kind" ]; then
# local kind="$(kubectl api-resources -o name | _inline_fzf | awk '{print $1}')"
# fi
# if _isClusterSpaceObject "$kind" ; then
# kubectl get "$kind" | _inline_fzf | awk '{print $1}' | xargs kubectl tree "$kind"
# else
# kubectl get "$kind" -A | _inline_fzf | awk '{print $1, $2}' | xargs kubectl tree "$kind" -n
# fi
# }
# [konsole] create root shell on a node
konsole() {
local node_hostname
node_hostname="$(kubectl get node --label-columns=kubernetes.io/hostname | _inline_fzf |\
awk '{print $6}')"
local ns
ns="$(kubectl get ns | _inline_fzf | awk '{print $1}')"
local name=shell-$RANDOM
local overrides='
{
"spec": {
"hostPID": true,
"hostNetwork": true,
"tolerations": [
{
"operator": "Exists",
"effect": "NoSchedule"
},
{
"operator": "Exists",
"effect": "NoExecute"
}
],
"containers": [
{
"name": "'$name'",
"image": "alpine",
"command": [
"/bin/sh"
],
"args": [
"-c",
"nsenter -t 1 -m -u -i -n -p -- bash"
],
"resources": null,
"stdin": true,
"stdinOnce": true,
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"tty": true,
"securityContext": {
"privileged": true
}
}
],
"nodeSelector": {
"kubernetes.io/hostname": "'$node_hostname'"
}
}
}
'
kubectl run $name --restart=Never --namespace $ns --rm -it --image alpine \
--overrides="${overrides}"
}
# [gkegpool] list gke node-pools
gkegpool() {
local project="$1"
[ -n "$project" ] && local ARGS="--project=$project"
local arg_pair
arg_pair=$( (printf "CLUSTER LOCATION\n"; gcloud container clusters list \
--format='value(name, location)' $ARGS) | column -t | _inline_fzf)
# [ -z "$arg_pair" ] && printf "kfor: no pods found. no forwarding.\n" && return
arg_pair=$(echo $arg_pair|awk \
'l=split($2,loc,"-") {if (l==3) {print $1, "--zone="$2} else {print $1, "--region="$2}}')
gcloud container node-pools list --cluster=$arg_pair --format='value(name)' $ARGS
}
# [gkedes] describe gke cluster/node-pool
gkedes() {
local kind="pool"
local arg_proj=""
if [ $# -eq 1 ]; then
echo $1 |grep -q "cluster\|pool" \
&& kind=$1 \
|| arg_proj="--project=$1"
elif [ $# -eq 2 ]; then
if echo $1 |grep -q "cluster\|pool"; then
kind=$1
arg_proj="--project=$2"
else
kind=$2
arg_proj="--project=$1"
fi
fi
local arg_aux
arg_aux=$( (printf "CLUSTER LOCATION\n"; gcloud container clusters list --format='
value(name, location)' $arg_proj) | column -t | _inline_fzf)
arg_aux=$(echo $arg_aux | awk 'l=split($2,loc,"-") {
if (l==3) {print $1, "--zone="$2}
else {print $1, "--region="$2}
}')
if [ "$kind" = "pool" ]; then
arg_aux="$( (printf "POOL\n"; gcloud container node-pools list --cluster=$arg_aux \
--format='value(name)' $arg_proj) |_inline_fzf) --cluster=$arg_aux"
fi
test "$kind" = "pool" && kind="node-pools" || kind=clusters
gcloud container $kind describe $arg_aux $arg_proj --format=yaml
}
# [gkecluster] gke cluster list
gkecluster() {
local project="$1"
[ -n "$project" ] && local ARGS="--project=$project"
gcloud container clusters list $ARGS
}
# [ksec] decode a value from a secret
ksec () {
ns=$(kubectl get ns | _inline_fzf | awk '{print $1}')
local secret=$(kubectl get secret -n "$ns" | _inline_fzf | awk '{print $1}')
local key=$(kubectl get secret -n "$ns" "$secret" -o json | jq -r '.data | to_entries[] | "\(.key)"' | _inline_fzf_nh)
kubectl view-secret -n "$ns" "$secret" "$key"
}
# [kinstall] Install the required kubectl plugins
kinstall() {
kubectl krew install tree
kubectl krew install view-secret
}
# [kupdate] Updates kubectl plugins
kupdate() {
kubectl krew upgrade
}
unset completion_wrapper
# [khelp] show this help message
khelp() {
echo "Usage of fubectl"
echo
echo "Reduces repetitive interactions with kubectl"
echo "Find more information at https://github.com/kubermatic/fubectl"
echo
echo "Usage:"
if [ -n "$ZSH_VERSION" ]
then
grep -E '^# \[.+\]' "${(%):-%x}"
else
grep -E '^# \[.+\]' "${BASH_SOURCE[0]}"
fi
}
# [htemplate] Render chart templates locally and display the output.
htemplate() {
# ex. htemplate jenkins/jenkins -f deploy/values-jcasc.yaml
# ex. htemplate . -f deploy/values-jcasc.yaml
CHART=${1}
ARGS=${@:2}
TMP_DIR=$(mktemp -d -t htemp-XXXX)
helm fetch --untar --untardir ${TMP_DIR} ${CHART}
helm template ${ARGS} ${TMP_DIR}/*
rm -rf $TMP_DIR
}
# ex: et:ts=2:sw=2:ft=sh: