Gitlab is an amazing platform for hosting source code but it can also automate the deployment of your website or application.

In this example, I’ll use a great static website generator named Hugo.

I’ll first show how to build the site and host it on gitlab pages, then how to send it to any other host.

Let’s assume that you already created the website and pushed it to your gitlab repository.

To enable the continuous integration, you simply have to create a .gitlab-ci.yml file.

image: monachus/hugo

variables:
  GIT_SUBMODULE_STRATEGY: recursive

pages:
  script:
  - hugo --buildFuture
  artifacts:
    paths:
    - public
    expire_in: 1 week
  only:
  - master

images allows the selection of a docker image used to build the site.

GIT_SUBMODULE_STRATEGY: recursive will ensure to load the theme submodule.

pages is a special job used to create gitlab pages. Your website will be automatically hosted there https://.gitlab.io//.

hugo is the command to generate the site to the public directory.

The artifacts defines the directories or files to keep in the job result.

only: master is to apply it only on the master branch.

If you want to host your site somewhere else, you need to change the .gitlab-ci.yml file like this:

image: monachus/hugo

variables:
  GIT_SUBMODULE_STRATEGY: recursive

stages:
  - build
  - deploy
  
build:
  stage: build
  script:
  - hugo --buildFuture
  artifacts:
    paths:
    - public
    expire_in: 1 week
  only:
  - master
  
deploy:
  stage: deploy
  only:
    - master
  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 public/ ./public_html  --ignore-time --parallel=10 --exclude-glob .git* --exclude .git/"

You need two different stages, one for building the site and the other for deploying it.

The pages job has just been replaced by build to avoid sending to the gitlab pages.

The deploy job uses the tftp tool to push the website to the host of your choice.

You need to define the $USERNAME, $PASSWORD and $HOST environment variable in Settings > CI/CD to make it work.

The site will then be automatically built and deployed when you push modifications to the repository.