GitLab Build and Deploy to a Server via SSH

January 22, 2018 0 Comments

GitLab Build and Deploy to a Server via SSH

 

 

Is to create a build and deployment process, where you tag to release to production, push to master to release to staging server via ssh scp. SIMPLE 😉

We are going to be using

  • Gitlab CI/CD
  • Angular Cli to build our sample project (with unit and e2e testing)
  • SSH SCP to move our files to server
  • SSHPASS to help escape ssh password prompt
npm install -g @angular/cli
ng new gitlabApp
cd gitlabApp
ng serve

you should see our app on http://localhost:4200

You can also run your e2e and unit test by using ng e2e and ng test respectively.

Lets assume you have Gitlab repo created, so we can create a gitlab-ci.yml under our root folder, so gitlab can pick it up and run through it. Will create two environment

  • Staging: when we push to master branch, this is triggered
  • Production: when we create a tag or release, this is triggered
For just the app build process

The above will just list the distribution files on the console, next step should push the generated files to server 👐 . Read more about gitlab ci/cd for more configurations here.

NB: don’t forget to add the new repo as a remote origin, so you can push to the repo

We are going to be using sshpass to perform our secured copy (scp) since we can’t perform ssh directly on CI since it will request for password, which we can’t respond to. With sshpass we can set our password via SSHPASS environment variable and it will auto respond to anything ending with assword you can change this based on the way it requests for password entry.

We are going to make use of beforescript to install our sshpass via apt-get like so apt-get update -qq && apt-get install -y -qq sshpass . Then run our scp command like so

export SSHPASS=$USERPASS
- sshpass -e scp -o stricthostkeychecking=no -r directory-to-copy user@host:path-to-copy-files-to

To set our $USER_PASS variable, we open our gitlab repo dashboard and navigate to Settings > CI/CD > Secret variables

Set Secret ENV variables

Our final .gitlab-ci.yml should look like this

Gitlab Final Script for Deploying Your App over SSH

Commit and push, then check your build job on gitlab ✌️

Tip: Oh if you are having error on permission denied while copying files to ssh server via scp you can check here

Yolla done.

Thanks to Jonas Felix for the build processing explained here and also for more on deploying to Surge 👍


Tag cloud