如何使用GitLab管道的密钥通过SSH连接到标签服务器? [英] How to connect to a taget server via SSH with a key from a GitLab pipeline?

查看:1268
本文介绍了如何使用GitLab管道的密钥通过SSH连接到标签服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



正如我所看到的,我需要使用ssh-keygen生成一个密钥在GitLab端,并将其添加到我想要连接的服务器。



我可以在管道期间生成密钥,但由于公钥未添加到目标服务器,这是没有意义的。



我想这是一个常见的情况,从CI建立到具有密钥的远程SSH连接。



如何使其工作?

解决方案

只要您想要,就可以从任何地方运行ssh-keygen您使用适当的服务器上的相应键。



这是您需要的:




    生成密钥对
  • 私人密钥复制到gitlab CI变量(让我们称之为 SSH_PRIVATE_KEY

  • public 键复制到服务器,gitlab将连接到并将其添加到您的〜/ .s sh / authorized_keys 文件

  • 告诉您的CI流水线,使用存储在Gitlab CI变量中的私钥$ / b $ b


为了做最后一步,只需将以下内容添加到脚本或before_script中的 .gitlab-ci.yml 感兴趣的工作部分:

   - '其中ssh-agent || (apt-get update -y&& apt-get install openssh-client -y)'
#运行ssh-agent(在构建环境中)
- eval $(ssh-agent -s )
#将存储在SSH_PRIVATE_KEY变量中的SSH密钥添加到代理存储
- ssh-add<(echo$ SSH_PRIVATE_KEY)
- mkdir -p〜/ .ssh
- '[[-f /.dockerenv]]&& echo -eHost * \\\
\tStrictHostKeyChecking no\\\
\\\
> 〜/ .ssh / config'

然后做你的SSH连接和voilà!



编辑:我不记得我第一次在哪里找到这个信息,但这里是: https://docs.gitlab.com/ee/ci/ssh_keys/README.html


I want to connect to a server via SSH with a public key when GitLab pipeline succeeds.

As I see, I need to generate a key with ssh-keygen on GitLab side and add it to server where I want to connect.

I can generate a key during the pipeline but as the public key is not added to the target server, it makes no sense.

I suppose it's a common scenario to connect from a CI build to a remote SSH with a key.

How can I make it work?

解决方案

You can run ssh-keygen from wherever you want as long as you use the appropriate keys on the appropriate server.

Here is what you need:

  • Generate a key pair
  • Copy the private key to a gitlab CI variable (let's call it SSH_PRIVATE_KEY)
  • Copy the public key to the server gitlab will connect to and add it to your ~/.ssh/authorized_keys file
  • Tell your CI pipeline to use the private key that is stored in the Gitlab CI variable

In order to do that last step, just add the following to your .gitlab-ci.yml in the script or before_script section of the job of interest:

- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
# Run ssh-agent (inside the build environment)
- eval $(ssh-agent -s)
# Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
- ssh-add <(echo "$SSH_PRIVATE_KEY")
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'

Then do your SSH connections and voilà !

EDIT: I couldn't remember where I had found this info the first time but here it is : https://docs.gitlab.com/ee/ci/ssh_keys/README.html

这篇关于如何使用GitLab管道的密钥通过SSH连接到标签服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆