Build and Deploy Your Hugo Site to a Server With Gitlab CI/CD

This is the short case about how I build and deploy Hugo site to my own server with Gitlab CI/CD.

Let’s assume you have a Gitlab repo created, so we need to create a gitlab-ci.yml under your root folder, so Gitlab can pick it up and run.

image: alpine:3.7

before_script:
  - mkdir -p ~/.ssh
  - echo -e "$DEPLOY_KEY" > ~/.ssh/id_rsa
  - chmod 600 ~/.ssh/id_rsa
  - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
  - apk update && apk add --update --no-cache openssh

variables:
  GIT_SUBMODULE_STRATEGY: recursive

deploy_production:
  stage: deploy
  environment: Production
  only:
    - master

  script:
    - echo $HUGO_VERSION
    - wget --quiet --output-document=hugo_${HUGO_VERSION}_Linux-64bit.tar.gz https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_Linux-64bit.tar.gz
    - tar -xf hugo_${HUGO_VERSION}_Linux-64bit.tar.gz && mkdir -p /usr/local/sbin && mv hugo /usr/local/sbin/hugo && rm -rf hugo_${HUGO_VERSION}_linux_amd64 && rm -rf hugo_${HUGO_VERSION}_Linux-64bit.tar.gz
    - /usr/local/sbin/hugo --source=. --destination=./public || exit 1
    - cd ./public
    - scp -i ~/.ssh/id_rsa -r . [email protected]:/var/www/public

We are going to be using ssh-key to perform our secured copy (scp). In the configuration above I will use the $DEPLOY_KEY variable. Within Gitlab you will need to set up a Secret Variable that holds the private part of an SSH key that has access to your deployment server, just navigate to Settings > CI/CD > Secret variables.

Hugo — Success Deploy