How to connect to a target server via SSH with a key from a GitLab pipeline?

安稳与你 提交于 2019-12-06 03:49:42

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/41491343/how-to-connect-to-a-target-server-via-ssh-with-a-key-from-a-gitlab-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!