-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkubectl-shell
executable file
·89 lines (79 loc) · 2.3 KB
/
kubectl-shell
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
#!/usr/bin/env bash
# kubectl-shell - Kubernetes wrapper for exec-ing into a pod
#
# Usage:
# kubectl-shell <pod-name> [-c container] [-s shell]
#
# Arguments:
# pod-name (required) Name of the pod.
# Options:
# -c (optional) Container to exec into within the pod.
# -s (optional) Shell to use (sh/bash/zsh). Default: bash.
set -euo pipefail
# display usage information
function usage() {
echo "Usage: kubectl shell <pod-name> [-c container] [-s shell]"
echo " pod-name: (required) Name of the pod"
echo " Optional Arguments:"
echo " -c: (optional) Container to exec into within the pod"
echo " -s: (optional) Shell to use (sh/bash/zsh). Default: bash"
exit 1
}
# Initialize variables
pod_name=""
container=""
shell="bash"
# Parse command-line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-s)
if [[ -z ${2:-} ]]; then
echo "Error: Missing argument for -s (shell)" >&2
usage
fi
shell="$2"
shift 2
;;
-c)
if [[ -z ${2:-} ]]; then
echo "Error: Missing argument for -c (container)" >&2
usage
fi
container="$2"
shift 2
;;
-*)
echo "Error: Unknown option: $1" >&2
usage
;;
*)
if [[ -z "$pod_name" ]]; then
pod_name="$1"
else
echo "Error: Too many arguments" >&2
usage
fi
shift
;;
esac
done
# Check if the pod name is provided
if [[ -z "$pod_name" ]]; then
echo "Error: Pod name is required" >&2
usage
fi
# Fetch the namespace of the pod
namespace=$(kubectl get pods --all-namespaces --field-selector metadata.name="$pod_name" -o jsonpath='{.items[0].metadata.namespace}' 2>/dev/null || true)
if [[ -z "$namespace" ]]; then
printf "Error: Unable to find namespace for pod \"%s\". Ensure the pod exists.\n" "$pod_name" >&2
exit 1
fi
# Build kubectl exec command
exec_command=("kubectl" "exec" "-it" "$pod_name" "-n" "$namespace")
if [[ -n "$container" ]]; then
exec_command+=("-c" "$container")
fi
exec_command+=("--" "$shell")
# Execute the command
echo "Executing: ${exec_command[*]}"
"${exec_command[@]}"