Save time deploying Laravel with Gitlab CI to Staging server

Save time deploying Laravel with Gitlab CI to Staging server

It’s kind of pain to SSH into staging server and run git pull whenever there’s any code change in Master repo for testing in the staging server.

It would save some time if whenever there’s a push to Master, Gitlab will automatically deploy the latest code to staging server for testers to test it out.

It’s confusing as there’s private key / public key, here’s a step by step guide to make things clear:

  1. Generate a SSH key pair in your Mac or PC, for Mac just run this in terminal: ssh-keygen
  2. Choose a name for your key pair
  3. Add the public key (the one end with .pub) to your Staging Server’s authorized_key
  4. Go to Gitlab – Project Setting – CI/CD – Variables – Add this variable: SSH_PRIVATE_KEY – [the generated Private key]
  5. Create a .gitlab-ci.yml at the root of your project repo with the following content:
  - apt-get update -qq
  - apt-get install -qq git
  # Setup SSH deploy keys
  - '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'

  type: deploy
    name: staging
    - ssh [email protected] "cd /var/www/ohmytalent-laravel && git checkout master && git pull origin master && chmod -R 777 storage && exit"
    - master

That’s it, just try to Push new code to your Gitlab repo, and track the progress in Gitlab – CI/CD – Pipelines

There’s a lot more can be done by Gitlab CI, this is just to automate the code deploying skipping testing. The process normally takes 1-2 minutes, could be slower comparing to manually pushing and pulling, but still, automation is good. 🙂