Interactive Bash Script for Quick Kubernetes Pod Access
This script checks for kubectl, validates the kubeconfig, lets you choose a namespace and pod, selects a shell, and then runs kubectl exec to open an interactive terminal inside the chosen Kubernetes pod.
This Bash script provides an interactive way to access a Kubernetes pod's terminal.
It first checks whether the
kubectlcommand is available; if not, it prints an error and exits. It then verifies that the user's kubeconfig file (
~/.kube/config) exists, prompting the user to obtain it from operations if missing.
The script prompts the user to choose a namespace (test or stg) and sets the corresponding namespace variable. It asks for a keyword to filter pods, lists matching pods, and asks the user to paste the full pod name.
Next, it asks the user to select a shell (bash or sh) and executes
kubectl exec -itwith the chosen namespace, pod name, and shell. If the user enters an invalid option, the script displays an error message.
All user prompts and conditional logic are implemented with
read -p,
casestatements, and
ifchecks.
Full script:
#!/bin/bash which kubectl > /dev/null 2>&1 if [ $? != 0 ];then echo "kubelet工具未安装,请先安装!!" exit fi if [ ! -f ~/.kube/config ];then echo "当前用户家目录下没有k8s集群配置文件.kube/config,请联系运维获取配置!" exit fi read -p $'请选择要操作的命名空间:\n1: test \n2: stg:\n' NAMESPACE case $NAMESPACE in 1) NAMESPACE=zzmed-test ;; 2) NAMESPACE=zzmed-stg ;; *) echo "请选择正确的命名空间1:test 2:stg" ;; esac read -p $'请输入要操作POD的关键字:\n' POD kubectl get pods -n $NAMESPACE -owide|grep $POD read -p $'请复制粘贴上方POD的全名,并回车:\n' PODNAME read -p $'请选择要操作的终端:\n1: bash \n2: sh:\n' BASH case $BASH in 1) BASH=bash ;; 2) BASH=sh ;; *) echo "请输入正确的终端1: bash 2: sh" ;; esac kubectl exec -it -n $NAMESPACE $PODNAME $BASHPractical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.