【问题标题】:SSH keys inside docker containerdocker容器内的SSH密钥
【发布时间】:2020-05-21 08:53:27
【问题描述】:

我有一个连接gitlab的脚本,我该如何正确地把它转移到一个容器中,以便它可以通过SSH连接到gitlab?

   if not os.path.exists(os.path.join(PATH_SAVE_SCHEMA, '.git')):
        repo = Repo.init(PATH_SAVE_SCHEMA)
        origin = repo.create_remote('origin', GIT_REMOTE_URL)
        config_writer = repo.config_writer()
        config_writer.set_value('user', 'name', GIT_USER_NAME)
        config_writer.set_value('user', 'email', GIT_USER_EMAIL)
        config_writer.set_value('http', 'sslverify', 'false')
        config_writer.release()
        origin.fetch()
        origin.pull(repo.refs[0].remote_head)
        repo.git.reset('--hard')
    else:
        repo = Repo(PATH_SAVE_SCHEMA)
        repo.git.reset('--hard')
        repo.remote('origin').pull('master')

现在我的容器正在运行,但它给出了一个错误

Cmd('git') failed due to: exit code(1)
cmdline: git pull -v origin master
stderr: 'fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.'

如何为Docker文件中的key指定命令? 我需要在 GitLab 存储库中输入密钥吗?

我的 docker 文件:

ARG SSH_PRIVATE_KEY
ARG SSH_PUBLIC_KEY
ARG SSH_KNOWN_HOSTS
RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_rsa
RUN echo "${SSH_PUBLIC_KEY}" > ~/.ssh/id_rsa.pub
RUN chmod 700 ~/.ssh/id_rsa
RUN chmod 700 ~/.ssh/id_rsa.pub
RUN echo "${SSH_KNOWN_HOSTS}" > ~/.ssh/known_hosts

【问题讨论】:

  • 在 Dockerfile 中安全地包含类似这样的凭据几乎是不可能的;最好从主机运行这样的命令。作为开发人员,如果docker build 序列尝试切换到不同的分支而不是仅仅构建我已经签出的分支,我也会感到惊讶。

标签: python docker gitlab-ci ssh-keys


【解决方案1】:

您没有在任何地方提供密码。

快速而简单的方法是在 git url 中指定你的密码:

<username>:<password>@github.com/<username>/<reponame>.git

但是您的密码将以明文形式出现在您的代码中。正确的方法是在to mount your secret as volume 中,即password.txt 文件。

更好的是使用ssh_key 并将其安装为卷。

【讨论】:

  • 因为现在脚本在主机上运行,​​访问是在SSH密钥上,但是我不知道如何把这个密钥放到容器中
【解决方案2】:

在构建映像期间,您可以将 ssh 密钥复制到某个“tmp”构建阶段,从 git 下载代码,然后在“main”构建阶段从“tmp”阶段复制该代码。

https://docs.docker.com/develop/develop-images/multistage-build/

最后图片中不应有任何关于ssh key的信息。

【讨论】:

    猜你喜欢
    • 2020-12-27
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2022-10-25
    相关资源
    最近更新 更多