git - 在 Dockerfile 中使用 git clone "ssh://"

标签 git docker ubuntu ssh gerrit

我正在尝试从 Dockerfile 中的 Gerrit 克隆公司存储库。

我没有问题将我的私有(private) SSH key 提供给图像而不将它们保留在那里(使用多阶段构建)。

我的问题是 Gerrit 上的公司 repo 需要通过 ssh 进行 git clone:

git clone "ssh://usr@gerrit.com:port/path/to/repo

我正在尝试通过 buildKit 实验来做到这一点。
Dockerfile 中的运行命令:
RUN --mount=type=ssh git clone usr@gerrit.com:port/path/to/repo /image/path

但这并没有告诉 git 使用 ssh,因此它只会使用其标准协议(protocol)和端口。

在 Dockerfile 中执行此操作会产生以下错误
#14 0.659 Cloning into '/image/path'...                                                                                                                                                                         
#14 0.890 Warning: Permanently added the ECDSA host key for IP address 'xxx.xxx.xxx.xxx' to the list of known hosts.
#14 6.740 Permission denied, please try again.
#14 6.774 Received disconnect from xxx.xxx.xxx.xxx port 22:2: Too many authentication failures
#14 6.774 Disconnected from xxx.xxx.xxx.xxx port 22
#14 6.774 fatal: Could not read from remote repository.
#14 6.774 
#14 6.774 Please make sure you have the correct access rights
#14 6.774 and the repository exists.

该错误清楚地表明它试图使用端口 22,尽管我另有说明。

如果我使用 RUN git clone "ssh://usr@gerrit.com:port/path/to/repo"它声明它找不到远程仓库。
此命令仅在 Dockerfile 中失败,因为这是我公司克隆我们的存储库的标准方法。

完整的 Dockerfile 在这里:
# syntax=docker/dockerfile:experimental
# Using multistage build, where intermediate stage is used for cloning private repo from gerrit
FROM ubuntu as intermediate

# install git
RUN apt-get update
RUN apt-get install -y git openssh-client

# add credentials on build
ARG SSH_PRIVATE_KEY
RUN mkdir /root/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > /root/.ssh/id_rsa && chmod 400 /root/.ssh/id_rsa

# Add gerrit to known hosts
RUN touch /root/.ssh/known_hosts
RUN ssh-keyscan gerrit.com >> /root/.ssh/known_hosts

# Clone our repo from gerrit
RUN --mount=type=ssh git clone usr@gerrit.com:port/path/to/repo /image/path

# Actual build stage here
FROM ubuntu:18.04
...

有没有其他方法可以显式使用 ssh 使用 git clone 时的连接在 Dockerfile ?

最佳答案

使用 ssh 时,您需要确保为 .ssh 设置正确的权限。目录和 private keys
设置/root/.ssh的权限目录到 700

/root/.ssh/id_rsa Dockerfile 中 600 的私钥

chmod 700 /root/.ssh && \
chmod 600 /root/.ssh/id_rsa

另外,请确保您的 ssh key 设置正确。在继续之前在本地测试它们。

关于git - 在 Dockerfile 中使用 git clone "ssh://",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639298/

相关文章:

json - 修改 json 文件中的一些属性

node.js - 如何从 npm (Nodejs 0.8.x) 安装 node-gitteh 模块

git - 如何自定义 diff git 以忽略码日期生成

git - 通过事件 FTP 克隆 git 存储库

macos - 为什么docker占用了这么多VIRT内存?

docker - 将 ARG 放在 Dockerfile 顶部会阻止层重用吗?

windows - 加载dll失败。找不到指定的模块

git - 浅克隆后推送到 github

git rm * 不会一次性删除所有文件

mysql - 如何使用带有测试数据的自定义 mysql docker 镜像进行本地开发