Skip to content

Commit 156053f

Browse files
committed
fix cleanup when context/namespace changes
1 parent 3a8a382 commit 156053f

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

kubectl-node_shell

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ set -e
44
kubectl=kubectl
55
generator=""
66
node=""
7+
nodefaultctx=0
8+
nodefaultns=0
79
cmd='[ "nsenter", "--target", "1", "--mount", "--uts", "--ipc", "--net", "--pid", "--", '
810
custom=false
911
if ! [ -p /dev/stdin ] && ! [ -p /dev/stdout ]; then
@@ -16,11 +18,13 @@ while [ $# -gt 0 ]; do
1618

1719
case $key in
1820
--context)
21+
nodefaultctx=1
1922
kubectl="$kubectl --context $2"
2023
shift
2124
shift
2225
;;
2326
--kubecontext=*)
27+
nodefaultctx=1
2428
kubectl="$kubectl --context=${key##*=}"
2529
shift
2630
;;
@@ -34,11 +38,13 @@ while [ $# -gt 0 ]; do
3438
shift
3539
;;
3640
-n | --namespace)
41+
nodefaultns=1
3742
kubectl="$kubectl --namespace $2"
3843
shift
3944
shift
4045
;;
4146
--namespace=*)
47+
nodefaultns=1
4248
kubectl="$kubectl --namespace=${key##*=}"
4349
shift
4450
;;
@@ -58,6 +64,10 @@ while [ $# -gt 0 ]; do
5864
esac
5965
done
6066

67+
# Set the default context and namespace to avoid situations where the user switch them during the build process
68+
[ "$nodefaultctx" = 1 ] || kubectl="$kubectl --context=$(kubectl config current-context)"
69+
[ "$nodefaultns" = 1 ] || kubectl="$kubectl --namespace=$(kubectl config view --minify --output 'jsonpath={.contexts..namespace}')"
70+
6171
while [ $# -gt 0 ]; do
6272
cmd="$cmd\"$1\", "
6373
custom=true
@@ -75,7 +85,7 @@ if [ -z "$node" ]; then
7585
fi
7686

7787
image="docker.io/library/alpine"
78-
pod="nsenter-$(env LC_ALL=C tr -dc a-z0-9 < /dev/urandom | head -c 6)"
88+
pod="nsenter-$(env LC_ALL=C tr -dc a-z0-9 </dev/urandom | head -c 6)"
7989

8090
# Check the node
8191
kubectl get node "$node" $context $kubeconfig >/dev/null || exit 1
@@ -116,7 +126,7 @@ EOT
116126
)"
117127

118128
# Support Kubectl <1.18
119-
m=$(kubectl version --client -o yaml | awk -F'[ :"]+' '$2 == "minor" {print $3+0}' )
129+
m=$(kubectl version --client -o yaml | awk -F'[ :"]+' '$2 == "minor" {print $3+0}')
120130
if [ "$m" -lt 18 ]; then
121131
generator="--generator=run-pod/v1"
122132
fi

0 commit comments

Comments
 (0)