如何使用 GitLab 管道中的密钥通过 SSH 连接到目标服务器? [英] How to connect to a target server via SSH with a key from a GitLab pipeline?
问题描述
当 GitLab 管道成功时,我想通过 SSH 使用公钥连接到服务器.
I want to connect to a server via SSH with a public key when GitLab pipeline succeeds.
如我所见,我需要在 GitLab 端使用 ssh-keygen 生成一个密钥,并将其添加到我要连接的服务器.
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.
我认为使用密钥从 CI 构建连接到远程 SSH 是一种常见情况.
I suppose it's a common scenario to connect from a CI build to a remote SSH with a key.
我怎样才能让它工作?
推荐答案
只要在适当的服务器上使用适当的密钥,您就可以从任何地方运行 ssh-keygen.
You can run ssh-keygen from wherever you want as long as you use the appropriate keys on the appropriate server.
这是你需要的:
- 生成密钥对
- 将 private 密钥复制到 gitlab CI 变量(我们称之为
SSH_PRIVATE_KEY
) - 将 public 密钥复制到 gitlab 将连接的服务器并将其添加到您的
~/.ssh/authorized_keys
文件中 - 告诉您的 CI 管道使用存储在 Gitlab CI 变量中的私钥
- 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
为了完成最后一步,只需将以下内容添加到您感兴趣的工作的脚本或 before_script 部分的 .gitlab-ci.yml
中:
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 *
StrictHostKeyChecking no
" > ~/.ssh/config'
然后进行 SSH 连接,瞧!
Then do your SSH connections and voilà !
我不记得第一次在哪里找到此信息,但在这里:https://docs.gitlab.com/ee/ci/ssh_keys/README.html
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屋!