Whenever we want to deploy a codebase to a server, we need to do lots of process like unit testing, linting, building, uploading it to the server, etc.
It is tedious, right? Why not automate it.
Just push those changes and let GitLab CI handle those tasks for you.
Step 1: Generating SSH Keys
In order to push the code from GitLab repo to our server, we need to authenticate GitLab CI.
To generate SSH key pair, open up your terminal and execute the following command.
[crayon-5dc9d39ddba7e047530497 class="sh"]ssh-keygen -t rsa -b 4096 -C email@example.com
And then enter the full path where you need to store the SSH key pairs.
Then SSH to your server
And then append the public key (deploy-ci.pub) in
Step 2: Setting up your CI environment variables
Just like your machine, you can also add environmental variables in your GitLab CI.
And you can access those variables in your CI.
Its under Settings > Variables tab.
[crayon-5dc9d39ddba84327412091 ]SSH_USER_NAME -> root
SERVER_IP -> Your server IP address
AUTO_DEPLOY_PRIVATE_KEY -> Private Key which we just created (deploy-ci)
APP_ROOT -> Path to where need to deploy the app
Instead of hardcoding those things in GitLab CI config I like to keep it as environmental variables.
- You don’t need to edit your CI config often.
- And you can just copy paste it your other projects and just change the env variables 🙂
Step 3: GitLab CI
Create a .gitlab-ci.yml file at the root of your repo. And when you push the code to your repo. GitLab would check and execute your tasks.
Basically, GitLab CI is a docker container which allows us to execute any Linux command you want to.
Just like I mentioned before we can do a lot of things like building, testing your code, etc.
For the sake of simplicity, I’m just deploying the code in my repo to my server.
Here’s GitLab config, You can just copy/paste it 🙂
[crayon-5dc9d39ddba87534382905 class="yml"]image: node:latest
- apt-get update -y
# install ssh-agent
- 'which ssh-agent || (apt-get install openssh-client -y )'
- 'which rsync || (apt-get install rsync -y )'
# run ssh-agent
- eval $(ssh-agent -s)
# add ssh key stored in AUTO_DEPLOY_PRIVATE_KEY variable to the agent store
- ssh-add <(echo "$AUTO_DEPLOY_PRIVATE_KEY")
# disable host key checking (NOTE: makes you susceptible to man-in-the-middle attacks)
- mkdir -p ~/.ssh
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
- rsync -r -v -e ssh . $SSH_USER_NAME@$SERVER_IP:$APP_ROOT --delete-before --exclude '.git'
- echo "Deployed!"
If you’ve customised it, just make sure to lint it