Set up Travis CI for your VPS Instance01.06.2019
Ever wanted to use continuous deployment on your project, but also didn't want to put up with the high costs associated with PaaS providers?
I use a single Lightsail instance to host all projects online. In this guide, I will show you how to set up a Continuous Deployment pipeline, using travis, that deploys to your own Lightsail instance.
If you haven't done so, head over to travis and create an account. Allow it access to the GitHub repository you want to deploy.
Once that's done, go to Lightsail and create your instance. To set up ssh on your local computer, head over to the profile page inside Lightsail. From there, you can download an SSH key file.
With the file downloaded, you can ssh into your instance using the following command:
ssh -i <path to downloaded keyfile> <ubuntu@myinstance>
After ssh'ing in, clone the repository you want to deploy. Then you can close your connection, that's all we need to do on the server.
On your local machine, copy the Lightsail key file to your local repository:
cp <path to downloaded keyfile> <path to repository/keyfile.pem>
Under no circumstances commit this file to the git repository. Doing so would let anyone access your server. Instead, run the following command:
travis encrypt-file keyfile.pem
This will output a file called
keyfile.pem.enc. You should add this file to git. Travis automatically added decryption keys to the pipeline, and will be able to decrypt the keyfile on its own servers, so it can access your Lightsail instance.
Make sure you also copy the line the
travis encrypt-file command told you to copy.
It's now time to create our
.travis.yml config file in the project root. Add the following config:
stages: - name: deploy if: branch = master jobs: include: - stage: deploy name: lightsail language: generic dist: trusty sudo: false addons: ssh_known_hosts: - <lightsailinstance> before_script: - <your decryption command> - eval "$(ssh-agent -s)" - mv keyfile.pem ~/.ssh/keyfile.pem - chmod 600 ~/.ssh/keyfile.pem script: - cat .travisdeploy.sh | ssh -i ~/.ssh/keyfile.pem ubuntu@<lightsailinstance>
In the file, replace
<lightsailinstance> by your IP or host name of the Lightsail instance. Replace the
<your decryption command> with the command
travis encrypt-file output, which you copied just before.
This config file will run the script
.travisdeploy.sh on the lightsail instance. But what should the
.travisdeploy.sh script contain?
It depends on what code you are deploying. But most likely, it will consist of the following:
#!/usr/bin/env bash cd <your repo> git pull <code to restart server>;
For instance, for my `docker-compose` workflow that I set up for this blog, the file looks like this:
#!/usr/bin/env bash cd ~/blog/blog git pull mvn install docker-compose down && docker-compose up --build -d;