使用场景
在k8s中查看日志,进入容器,升级服务是日常工作中经常用到的场景,但是k8s不方便的地方在于批量升级和需要打出较长命令才能执行操作,涉及一些服务名雷同的服务先需要找到服务的pod,再执行kubectl相关命令,本脚本将以简易交互的方式解决上述问题
查看日志:
[root@beta-new-node2 ~]# ktool --help
Usage: ktool -u 批量升级镜像
-c 查看升级情况
-e 编辑镜像
log service_keywords 查看pod日志
exec service_keywords 进入pod
[root@beta-new-node2 ~]# ktool log icy
1 : icy-alert-provider-68f758746-ckkkg
2 : icy-community-provider-6d7c67c975-9n6ws
3 : icy-device-provider-7b9ccd89d6-jtr26
4 : icy-frontend-5f6797577b-s9h5z
5 : icy-message-provider-59b469569-278xg
6 : icy-oauth-provider-cc858ffb9-x5lv5
请输入要操作的pod序号
升级镜像:输入ktool -e后会进入vim编辑,在此处填入镜像地址,之后执行ktool -u
[root@beta-new-node2 shell]# ktool -u
deployment.apps/icy-alert-provider image updated
icy-alert-provider-68f758746-ckkkg 1/1 Running 0 22m
icy-alert-provider-7c8f77559-9bf6d 0/1 ImagePullBackOff 0 2m15s
实现
批量升级:将镜像地址分割出服务名,先过滤出pod名,再利用kubectl set image的命令进行升级
执行log,exec命令:先根据用户输入的服务关键词过滤出pod名并存入一个数组中,再用一个字典去接收该数组,key为数字i,value为pod名,之后遍历字典打印出key和value,提示用户输入编号,也就是字典中的key,拿出key对应的value–pod名后就可以实现操作pod的目的
#!/bin/bash
cd /opt/shell
service_conf="image-list.conf"
service_list=()
order=$1
service_keywords=$2
usage() {
echo "Usage: ktool -u 批量升级镜像"
echo " -c 查看升级情况"
echo " -e 编辑镜像"
echo " log service_keywords 查看pod日志"
echo " exec service_keywords 进入pod"
exit 1
}
editimage(){
vim /opt/shell/image-list.conf
}
upgrade(){
i=0
>result.log
while read -r conf_line; do
service_name=`echo ${conf_line}|awk -F '————' '{print $1}'| awk -F '/' '{print $3}'|awk -F ':' '{print $1}'`
image=`echo ${conf_line}|awk -F '————' '{print $1}'`
kubectl set image deployment/${service_name} jar=${image}
service_list[$i]=${service_name}
((i++))
done < ${service_conf}
for service in ${service_list[@]}
do
# sleep 1
kubectl get pods|grep ${service} >> result.log
done
cat result.log
}
check(){
while read -r conf_line; do
service_name=`echo ${conf_line}|awk -F '————' '{print $1}'| awk -F '/' '{print $3}'|awk -F ':' '{print $1}'`
kubectl get pods|grep ${service_name}
done < ${service_conf}
}
order(){
declare -A service_dict
service_list=`kubectl get pods |grep ${service_keywords}|awk '{print $1}'`
i=1
for service in ${service_list[@]}
do
service_dict[$i]=$service
((i++))
done
for key in $(echo ${!service_dict[*]})
do
echo "$key : ${service_dict[$key]}"
done
echo "请输入要操作的pod序号"
read input
if [ $order = "log" ];then
echo "kubectl logs -f ${service_dict[$input]}"
kubectl logs -f ${service_dict[$input]}
elif [ $order = "exec" ];then
echo "kubectl exec -it ${service_dict[$input]} bash"
kubectl exec -it ${service_dict[$input]} bash
fi
}
main(){
case "$1" in
"-u")
upgrade
;;
"-c")
check
;;
"-e")
editimage
;;
"log")
order
;;
"exec")
order
;;
*)
usage
;;
esac
}
main $1