如何使用GitLab管道中的密钥通过SSH连接到目标服务器?
当GitLab管道成功时,我想使用公钥通过SSH连接到服务器。
I want to connect to a server via SSH with a public key when GitLab pipeline succeeds.
如我所见,我需要使用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.
这里是您需要的:
- 生成密钥对
- 将私有密钥复制到gitlab CI变量(我们将其称为
SSH_PRIVATE_KEY
) - 将 public 键复制到服务器上,gitlab将连接到该服务器并将其添加到您的
〜/ .ssh / authorize d_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 *\n\tStrictHostKeyChecking no\n\n" > ~/.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