You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kubernetes Secret实现SSH认证时遭遇只读文件系统错误求助

解决方案

方案1:挂载Secret中的单个密钥文件而非整个目录

不要将整个/root/.ssh目录挂载为Secret,而是仅挂载Secret中的id_rsa和id_rsa.pub文件到该目录下。这样/root/.ssh目录本身是Pod内的可写目录,可正常创建或修改known_hosts。

修改Pod配置如下:

volumes:
  - name: test-ssh
    secret:
      secretName: test-ssh
containers:
  # 你的Jenkins容器配置
  volumeMounts:
    - name: test-ssh
      mountPath: "/root/.ssh/id_rsa"
      subPath: id_rsa
      readOnly: true
    - name: test-ssh
      mountPath: "/root/.ssh/id_rsa.pub"
      subPath: id_rsa.pub
      readOnly: true

配置完成后,Pod启动时/root/.ssh目录保持可写权限,执行ssh-keyscan github.com >> ~/.ssh/known_hosts即可成功。

方案2:使用emptyDir结合Init容器复制密钥

若需保持/root/.ssh目录的完整挂载,可通过emptyDir(可写临时存储)结合Init容器,将Secret中的密钥复制到emptyDir后再挂载到/root/.ssh。

Pod配置示例:

volumes:
  - name: ssh-secret
    secret:
      secretName: test-ssh
  - name: ssh-dir
    emptyDir: {}

initContainers:
  - name: copy-ssh-keys
    image: busybox:latest
    command:
      - sh
      - -c
      - |
        cp /ssh-secret/id_rsa /ssh-dir/id_rsa
        cp /ssh-secret/id_rsa.pub /ssh-dir/id_rsa.pub
        chmod 600 /ssh-dir/id_rsa
        chmod 644 /ssh-dir/id_rsa.pub
    volumeMounts:
      - name: ssh-secret
        mountPath: /ssh-secret
      - name: ssh-dir
        mountPath: /ssh-dir

containers:
  - name: jenkins-container
    # 你的容器镜像、命令等配置
    volumeMounts:
      - name: ssh-dir
        mountPath: /root/.ssh

Init容器会将Secret中的密钥复制到可写的emptyDir中,主容器挂载该emptyDir到/root/.ssh后,即可正常修改目录内的文件。

方案3:预先将known_hosts加入Secret

如果不需要动态生成known_hosts,可预先生成该文件并加入Secret,挂载后直接使用。

  1. 预先生成GitHub的known_hosts文件:
ssh-keyscan github.com > known_hosts
  1. 创建包含三个文件的Secret:
kubectl create secret generic test-ssh --from-file=id_rsa=id_rsa --from-file=id_rsa.pub=id_rsa.pub --from-file=known_hosts=known_hosts --namespace jenkins
  1. 保持原有的整个目录挂载配置即可,此时/root/.ssh/known_hosts已存在,无需再执行添加命令。

内容的提问来源于stack exchange,提问作者Prasann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:31