1. Kubernetes脚本开发实战指南
在云原生时代,Kubernetes已经成为容器编排的事实标准。作为一线运维工程师,我每天都要处理大量与Kubernetes相关的自动化任务。今天想分享的是如何通过Shell和Python脚本来提升Kubernetes管理效率的实战经验,这些脚本已经在我们生产环境稳定运行超过两年。
提示:本文所有脚本示例都经过脱敏处理,可以直接用于测试环境,但生产环境使用前请务必根据实际情况调整参数校验和错误处理。
1.1 为什么需要Kubernetes脚本
当你的集群规模超过20个节点时,通过kubectl命令行手动操作就会变得效率低下。我们团队遇到过几个典型痛点:
- 批量部署应用时,需要反复修改yaml文件中的镜像版本
- 排查问题时要手动收集多个Pod的日志和描述信息
- 定期清理Evicted状态的Pod等资源
通过脚本自动化这些操作后,我们的日常运维效率提升了60%以上。下面这个简单的资源检查脚本就能替代10余条手动命令:
bash复制#!/bin/bash
# 检查集群基础资源状态
echo "=== 节点资源 ==="
kubectl get nodes -o wide
echo -e "\n=== Pod状态统计 ==="
kubectl get pods --all-namespaces -o wide | awk '{print $4}' | sort | uniq -c
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. Shell脚本开发实战
2.1 基础模板与最佳实践
一个健壮的Kubernetes管理脚本应该包含以下要素:
bash复制#!/bin/bash
set -eo pipefail # 严格错误处理
# 配置区
CLUSTER_NAME="production"
CONTEXT="k8s-$CLUSTER_NAME"
NAMESPACE="${1:-default}" # 支持传参指定namespace
# 预检查
if ! command -v kubectl &> /dev/null; then
echo "错误:未检测到kubectl命令"
exit 1
fi
# 主逻辑
function main() {
kubectl config use-context "$CONTEXT"
# 实际业务逻辑...
}
# 执行入口
main "$@"
注意:一定要设置set -eo pipefail,这样脚本会在任何命令失败时立即退出,避免隐藏错误。
2.2 实用脚本示例
2.2.1 批量滚动更新Deployment
这是我们在周四发布日使用最多的脚本:
bash复制#!/bin/bash
# 参数:Deployment名称 新镜像版本
DEPLOYMENT=$1
NEW_IMAGE=$2
if [ $# -ne 2 ]; then
echo "用法: $0 <deployment名称> <新镜像>"
exit 1
fi
kubectl set image deployment/$DEPLOYMENT "*=$NEW_IMAGE"
kubectl rollout status deployment/$DEPLOYMENT -w
使用示例:
bash复制./update_deployment.sh frontend-service registry.cn-hangzhou.aliyuncs.com/company/frontend:v1.2.3
2.2.2 智能日志收集器
这个脚本可以自动收集问题Pod及其关联资源的日志:
bash复制#!/bin/bash
POD_NAME=$1
# 获取Pod基本信息
echo "=== Pod $POD_NAME 描述 ===" > debug.log
kubectl describe pod $POD_NAME >> debug.log
# 获取容器日志
for container in $(kubectl get pod $POD_NAME -o jsonpath='{.spec.containers[*].name}'); do
echo -e "\n=== 容器 $container 日志 ===" >> debug.log
kubectl logs $POD_NAME -c $container --tail=100 >> debug.log
done
# 获取关联事件
echo -e "\n=== 相关事件 ===" >> debug.log
kubectl get events --field-selector involvedObject.name=$POD_NAME >> debug.log
3. Python脚本进阶开发
当需要更复杂的逻辑处理时,Python是更好的选择。推荐使用官方client-go的Python版本:kubernetes-py。
3.1 环境准备
bash复制pip install kubernetes
3.2 Python脚本示例
3.2.1 集群资源报告生成器
python复制from kubernetes import client, config
import datetime
def generate_cluster_report():
config.load_kube_config()
v1 = client.CoreV1Api()
report = f"Kubernetes集群报告 {datetime.datetime.now()}\n\n"
# 节点信息
nodes = v1.list_node()
report += f"节点数: {len(nodes.items)}\n"
for node in nodes.items:
report += f"- {node.metadata.name}: {node.status.capacity['cpu']} CPU, {node.status.capacity['memory']}\n"
# Pod统计
pods = v1.list_pod_for_all_namespaces()
report += f"\n总Pod数: {len(pods.items)}\n"
return report
if __name__ == "__main__":
print(generate_cluster_report())
3.2.2 自定义HPA控制器
当内置HPA不能满足需求时,可以用Python实现自定义扩缩容逻辑:
python复制from kubernetes import client, config
import time
config.load_kube_config()
apps_v1 = client.AppsV1Api()
autoscaling_v1 = client.AutoscalingV1Api()
def check_and_scale(deployment_name, namespace="default"):
# 自定义业务指标检查逻辑
current_load = get_business_metrics() # 实现你自己的指标获取
# 获取当前HPA配置
hpa = autoscaling_v1.read_namespaced_horizontal_pod_autoscaler(
f"{deployment_name}-hpa",
namespace
)
# 根据业务指标调整副本数
new_replicas = calculate_replicas(current_load, hpa.spec.min_replicas, hpa.spec.max_replicas)
if new_replicas != hpa.status.current_replicas:
patch = {"spec": {"replicas": new_replicas}}
apps_v1.patch_namespaced_deployment_scale(
deployment_name,
namespace,
patch
)
print(f"已将 {deployment_name} 调整为 {new_replicas} 个副本")
while True:
check_and_scale("payment-service")
time.sleep(60) # 每分钟检查一次
4. 安全与权限管理
4.1 Service Account配置
为脚本创建专用的Service Account:
bash复制kubectl create serviceaccount script-runner
kubectl create clusterrole script-runner \
--verb=get,list,watch,create,patch \
--resource=pods,deployments,services
kubectl create clusterrolebinding script-runner \
--clusterrole=script-runner \
--serviceaccount=default:script-runner
然后在Python脚本中这样使用:
python复制from kubernetes import client, config
# 使用Service Account token
config.load_incluster_config()
4.2 RBAC最佳实践
遵循最小权限原则:
- 为不同功能的脚本创建不同的Service Account
- 按namespace划分权限范围
- 定期审计脚本使用的权限
5. 调试与优化技巧
5.1 常见问题排查
问题1:脚本在本地可以运行,但在集群内报权限错误
解决方案:
bash复制# 检查Service Account是否正确挂载
kubectl describe pod my-pod | grep Mounts -A5
# 检查RBAC绑定
kubectl get clusterrolebinding -o wide | grep script-runner
问题2:脚本执行速度慢
优化建议:
- 使用
--chunk-size=500参数处理大量资源 - 并行化请求(Python可使用asyncio)
- 缓存不常变的数据
5.2 性能优化示例
并行获取所有Pod日志的Python实现:
python复制import asyncio
from kubernetes.client import CoreV1Api
from kubernetes.stream import stream
async def get_pod_log(pod_name, namespace):
v1 = CoreV1Api()
return stream(
v1.connect_get_namespaced_pod_log,
pod_name,
namespace,
follow=False
)
async def main():
pods = ["pod1", "pod2", "pod3"] # 获取实际Pod列表
tasks = [get_pod_log(pod, "default") for pod in pods]
logs = await asyncio.gather(*tasks)
for pod_name, log in zip(pods, logs):
print(f"=== {pod_name} 日志 ===")
print(log)
asyncio.run(main())
6. 版本控制与持续集成
6.1 脚本管理规范
我们团队采用这样的目录结构:
code复制k8s-scripts/
├── bin/ # 可执行脚本
├── lib/ # 公共函数库
├── config/ # 环境特定配置
├── tests/ # 测试用例
└── README.md # 使用文档
6.2 CI/CD集成示例
GitLab CI配置示例:
yaml复制stages:
- test
- deploy
lint-scripts:
stage: test
image: alpine/shellcheck
script:
- shellcheck bin/*.sh
deploy-scripts:
stage: deploy
image: bitnami/kubectl
script:
- kubectl create configmap k8s-scripts --from-file=bin/ -n automation
only:
- master
7. 高级应用场景
7.1 自定义控制器开发
使用Python实现简单的控制器逻辑:
python复制from kubernetes import client, config, watch
config.load_kube_config()
v1 = client.CoreV1Api()
def handle_pod_event(event):
pod = event['object']
if event['type'] == 'ADDED' and pod.metadata.annotations.get('special') == 'true':
print(f"发现特殊Pod: {pod.metadata.name}")
# 实现你的自定义逻辑
w = watch.Watch()
for event in w.stream(v1.list_pod_for_all_namespaces):
handle_pod_event(event)
7.2 与Prometheus集成
获取指标数据并自动处理:
python复制import requests
from kubernetes import client, config
def get_pod_cpu_usage(pod_name, namespace):
prom_url = "http://prometheus-server/api/v1/query"
query = f'sum(rate(container_cpu_usage_seconds_total{{pod="{pod_name}", namespace="{namespace}"}}[1m])) by (pod)'
response = requests.get(prom_url, params={'query': query})
results = response.json()['data']['result']
if results:
return float(results[0]['value'][1])
return 0.0
这些脚本只是Kubernetes自动化管理的冰山一角。在实际使用中,我们还需要考虑日志记录、监控告警、错误恢复等生产级需求。建议从简单脚本开始,逐步构建适合自己业务场景的工具集。
