GitLab CI - Auto Deploy to your VPS
I was developing a project where I wanted to have an online Staging environment to host our application and have the latest changes being deployed automatically upon each merge request to the Staging branch.
I’ve started by searching how to setup automatic deploy via my .gitlab-ci.yml file, the main goal would be to run our pipeline and, if my test cases were successful, we would SSH into my VPS and pull the latest version of the branch.
GitLab documentation has a good basic tutorial that will prepare your GitLab Runner before your pipeline gets executed, but that script wasn’t really working for me at time of writing. So I’ve decided to follow a different approach and add my deploy code to the execution of the pipeline itself which has been working pretty consistently so far.
Pre-requirements:
cat ~/.ssh/gitlab.pub >> ~/.ssh/authorized_keys
Step 1: CI Configuration file
If you don’t currently have a CI file, please add one to your project root directory.
领英推荐
touch .gitlab-ci.yml
This file will be executed by a GitLab Runner every time you push to your remote branch.
Step 2: CI Pipeline
The following code should be added to your CI file as it will work as your pipeline when you push to your remote repo.
stages:
- deploy_staging
deploy_staging:
# variables:
# CI_DEBUG_TRACE: "true"
stage: deploy_staging
environment: staging
script:
- 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
- eval $(ssh-agent -s)
- echo "$STAGING_PRIVATE_KEY" | tr -d '\r' | ssh-add -
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh <username>@<VPS-Pub-IP> -t -t -o StrictHostKeyChecking=no "cd <project-repository> && git checkout staging && git pull && exit"
only:
- staging
A short breakdown of the above code:
Note: The variables section inside the “deploy_staging” is commented out since that code can be used to set your pipeline to debug mode, it can be a good way to analyze if your private key is being stored in the proper way. Before using it, please read the documentation from GitLab.