28 May 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:
- Generate a SSH key pair in your Mac or PC, for Mac just run this in terminal: ssh-keygen
- Choose a name for your key pair
- Add the public key (the one end with .pub) to your Staging Server’s authorized_key
- Go to Gitlab – Project Setting – CI/CD – Variables – Add this variable: SSH_PRIVATE_KEY – [the generated Private key]
- Create a .gitlab-ci.yml at the root of your project repo with the following content:
before_script: - 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' deploy_staging: type: deploy environment: name: staging url: ohmytalent-staging.artisan.com.my script: - ssh [email protected] "cd /var/www/ohmytalent-laravel && git checkout master && git pull origin master && chmod -R 777 storage && exit" only: - 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. 🙂