如何使用 Docker 中的部署密钥从 Github 部署代码?

How to deploy code from Github using deploy key in Docker?

我想在构建时将代码从 Github 提取到我的 Docker 图像中。我有一个从存储库生成的部署密钥,但在我看来 ssh-agent 没有在我的 Docker 图像上工作。

我做了什么(我的Docker文件):

FROM python:2.7-stretch
ADD ./id_rsa /root/.ssh/id_rsa
RUN eval "$(ssh-agent -s)"
RUN ssh-add -K /root/.ssh/id_rsa

输出:

Step 12/22 : RUN eval "$(ssh-agent -s)"
 ---> Running in f9ad80981cee
Agent pid 6
Removing intermediate container f9ad80981cee
 ---> d773f7ce5917
Step 13/22 : RUN ssh-add -K /root/.ssh/id_rsa
 ---> Running in 95efeed6a7ad
Could not open a connection to your authentication agent.
The command '/bin/sh -c ssh-add -K /root/.ssh/id_rsa' returned a non-zero code: 2

如您所见,ssh-agent 已启动,但未添加密钥。

如果我跳过 ssh-add 步骤,那么我的 git pull 稍后会因为特权而失败,这正如预期的那样失败,因为没有进行身份验证。

实际上你不需要将你的私钥复制到你的容器中(你最好不要这样做)。

您只需要在主机和 docker 容器上安装并启动 ssh-agent 然后您需要做的就是挂载 ssh-aget 的套接字文件:

如果您正在使用docker-compose:

environment:
  - "SSH_AUTH_SOCK=/tmp/ssh-agent"
volumes:
  - $SSH_AUTH_SOCK:/tmp/ssh-agent

docker:

docker run -v $SSH_AUTH_SOCK:/tmp/ssh-agent 8be57bbc9561 sleep 1000000 # 8be57bbc9561 is an id of the image
docker exec -it -e SSH_AUTH_SOCK=/tmp/ssh-agent 5b6f4a8f8661 /bin/ash # 5b6f4a8f8661 is an id of the container

P.S

就您的情况而言,我认为问题可能与 export 命令有关,该命令通常是 ssh-agent 输出代码中的 evaled

它应该为您提供两个变量:SSH_AUTH_SOCKSSH_AGENT_PID。但是 export 不会跨图像持续存在。

您已使用 RUN 两次:第一次用于启动 ssh-agent 和导出变量,然后用于添加密钥。每个 Dockerfile 指令都会生成一个中间容器(并且导出不会在它们之间持续存在)。

如果你仍然想以这种方式使用它(我强烈建议避免),你可以尝试在一个 RUN 中绑定这两个命令:

RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa

我根据上面的回答写了一篇short post

编辑~/.ssh/config

使用新密钥添加

Host github.com
IdentityFile /root/.ssh/id_rsa

从这个link:

The -K option is Apple's standard version of ssh-add, which stores the passphrase in your keychain for you when you add an ssh key to the ssh-agent.

If you don't have Apple's standard version installed, you may receive an error.

尝试删除-K 选项并重新构建它。以下对我有用:

FROM python:2.7-stretch
ADD ./id_rsa /root/.ssh/id_rsa
RUN eval "$(ssh-agent -s)" && ssh-add /root/.ssh/id_rsa