如何通过Python脚本登录Kubernetes Pod并修改内部的yaml文件
实现步骤指引
1. 前置准备
- 安装Kubernetes官方Python客户端:
pip install kubernetes - 确保本地有可用的Kubeconfig配置(默认读取
~/.kube/config,和kubectl使用的配置一致即可)
2. 核心逻辑实现
Kubernetes Python客户端的stream接口可以实现和kubectl exec完全一致的能力,支持执行单条命令、交互式登录两种场景。
2.1 执行单条命令(示例:查看Pod内文件)
from kubernetes import client, config from kubernetes.stream import stream # 加载本地kubeconfig配置,集群内运行时替换为config.load_incluster_config() config.load_kube_config() v1 = client.CoreV1Api() # 自定义参数:命名空间、目标Pod名称 namespace = "default" pod_name = "替换为实际Pod名称" # 示例命令:查看Pod内/opt/config.yaml的内容 exec_command = ["/bin/sh", "-c", "cat /opt/config.yaml"] # 调用exec接口执行命令 resp = stream(v1.connect_get_namespaced_pod_exec, pod_name, namespace, command=exec_command, stderr=True, stdin=False, stdout=True, tty=False) print("命令执行结果:\n", resp)
2.2 非交互式修改Pod内YAML文件
如果已经明确要修改的内容,可以直接通过命令重写目标文件,无需进入交互式终端:
from kubernetes import client, config from kubernetes.stream import stream config.load_kube_config() v1 = client.CoreV1Api() namespace = "default" pod_name = "替换为实际Pod名称" # 替换为你要写入的新YAML内容 new_yaml = """apiVersion: v1 kind: Config metadata: name: test-config data: key: new-value """ # 构造写入文件的命令 exec_command = ["/bin/sh", "-c", f"cat > /opt/config.yaml << 'EOF'\n{new_yaml}\nEOF"] resp = stream(v1.connect_get_namespaced_pod_exec, pod_name, namespace, command=exec_command, stderr=True, stdin=False, stdout=True, tty=False) # 执行无报错即写入成功,可再调用cat命令验证内容
2.3 交互式登录Pod(和kubectl exec -it效果一致)
如果需要手动编辑文件(比如用vim修改),可以开启stdin和tty实现交互式终端:
import sys import termios import tty from kubernetes import client, config from kubernetes.stream import stream def interactive_shell(ws): oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) ws.settimeout(0.0) while True: if ws.is_open(): try: o = ws.read_stdout() if o: sys.stdout.write(o) sys.stdout.flush() except: pass try: i = sys.stdin.read(1) if i: ws.write_stdin(i) except: pass finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) if __name__ == "__main__": config.load_kube_config() v1 = client.CoreV1Api() namespace = "default" pod_name = "替换为实际Pod名称" # 启动交互式bash,容器无bash则替换为/bin/sh exec_command = ["/bin/bash"] resp = stream(v1.connect_get_namespaced_pod_exec, pod_name, namespace, command=exec_command, stderr=True, stdin=True, stdout=True, tty=True) interactive_shell(resp)
运行脚本后直接进入Pod终端,即可使用vim等工具手动编辑内部YAML文件。
3. 注意事项
- 若修改的是挂载的ConfigMap/Secret对应的文件,修改内容会被Kubernetes自动覆盖,这类配置不要直接在Pod内修改,建议直接调整对应的K8s资源
- 确保Pod对应容器有目标文件的写权限,且容器内安装了需要的工具(精简镜像可能无vim等编辑工具)
- 容器内无sh时,把命令中的
/bin/sh替换为容器支持的shell路径即可
内容的提问来源于stack exchange,提问作者hazel
相关产品推荐
相关产品推荐

