- Make sure you can connect to your server via your ssh-key without requiring password.
- On gitlab, go to your repository > settings > CI/CD > Variables
- Add a new variable SSH_PRIVATE_KEY. The value is your ssh private key (e.g content of ~/.ssh/id_rsa)
- Add the file below to your project
before_script: - apt-get update -qq - apt-get install -qq git - "which ssh-agent || ( apt-get install -qq openssh-client )" - eval $(ssh-agent -s) - ssh-add <(echo "$SSH_PRIVATE_KEY") - mkdir -p ~/.ssh - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' deploy: type: deploy script: - ssh firstname.lastname@example.org "pwd && ls" only: - main
After that you need to run this command because You need to add the public key to the server so it would be recognized as an authentication key.
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Just consider to change
email@example.com the use and also the IP address.
Now if you push to the main branch it will run the pipeline and then run the command on your server :))
In the next article we use this to deploy our project to the server automatically
That is all