mrkaluzny homepage
Tips & Tricks

How to deploy any project using FTP with Gitlab Continous Integration (CI)?

Jun 19, 2019

Using FTP programs to add every change on your projects is not only annoying but also time-consuming. Fortunately, there’s a quick fix for that, which is going to save you lots of time in the long run.

This solution is called Gitlab Pipelines. I prefer to use Gitlab for my commercial projects over GitHub or BitBucket, why? Well, it’s free and way better than the both mentioned above. One of the features I love is built-in Continous Integration which allows you to build, test and deploy committed code without any effort, while you can take your time coding another feature.

So how does it work?

The first step to configure your pipeline is adding a new file called `.gitlab-ci.yml` to your repo.

In this file, you can define stages and task that need to be completed in each stage. For this example, all we need is a deployment stage.

To define this stage we have to:

deploy: // You can name your task however you like
    stage: deploy

After that, you can define which branches should be taken into account when committing new changes. The obvious choice would be master branch, then you can safely develop using other branches and deploy finished product.

deploy: // You can name your task however you like
    stage: deploy
    only:
        - master

The last step is to add a script that will allow you to transfer files using FTP:

deploy: // You can name your task however you like
    stage: deploy
    only:
        - master
        deploy:
  script:
    - apt-get update -qq && apt-get install -y -qq lftp
    - lftp -c "set ftp:ssl-allow no; open -u $USERNAME,$PASSWORD $HOST; mirror -Rev dist/ ./public_html  --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/"

Let’s go line by line here:

apt-get is Advanced Packaging Tool that’s installing lftp tool (you can read more about it here). When lftp is installed the script will use it to connect with the server using passed in credentials ($HOST, $USERNAME, $PASSWORD which are defined in Pipelines settings).

Then the script defines what to do with selected files mirror -Rev. In this setting -R stands for a reverse mirror, so it puts files on a server, e deletes files on the server not present in the repo (so make sure to make a backup first!) and v stands for verbose.

In this case, the script is going to copy everything in the dist folder (to copy every file in the repo you just have to put in ./ and send it to public_html on the server. Next options define how many files can be uploaded simultaneously (in this case 10). —exclude-glob allows us to exclude some files (here we’re excluding .git).

Adding this file to your repo will automatically enable the pipeline on every commit to master branch, just remember to define variables in the settings (this way your sensitive information stays hidden from people visiting your repo).