Deploy a static website to Netlify using GitLab's CI/CD pipeline

Goal#

Instead of using Gitlab pages, using Netlify has a web host has the following advantages:

  • automatic Let's encrypt certificate + auto-renewing (now also available on Gitlab)
  • managed DNS zone at the same place

But still using the Gitlab CI/CD over a fully managed Netlify pipeline have the following advantages:

  • advanced CI/CD for more complex deployment workflow

Install netlify-cli#

Install netlify-cli globally with npm i netlify-cli -g. You can check it is properly installed with netlify -v.

Preparing Netlify for CI/CD#

In your git repository, run netlify init --manual and follow the wizard steps.

The site ID will be saved locally in .netlify/state.json.

Generate a personal access token#

If this is the first time you're doing this:

Login to Netlify, then go to User Settings > Applications (https://app.netlify.com/user/applications) and create a new access token.

Save it, once the page is exited you won't be able to get it again.

If you lose it, you'll need to generate a new one.

Setup Netlify's config file#

You won't need netlify.toml because we will use only .gitlab-ci.yml.

Preparing for GitLab CI/CD#

Assuming you already have a proper .gitlab-ci.yml file for you project; you then have to setup environment variables in Gitlab.

In your Gitlab project go to Settings > CI/CD and expand the Variables section.

Add in NETLIFY_AUTH_TOKEN and NETLIFY_SITE_ID.

You should have something like this:

Note: it is recommended to add .netlify/state.json in its .gitignore to avoid pushing it in the git repository.

Modifying the CI/CD pipeline#

Example of project .gitlab-ci.yml where I use Netlify:

I won't explain how to build a proper Gitlab CI/CD configuration file because there are already many resources for that.

I'll rather explain what you need to add:

  1. Either in before_script: or in a stage script: add npm install netlify-cli -g
  2. In pages: (stage: deploy) add to your script: this step netlify deploy --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --prod --dir public/ where --dir value is the directory to deploy.

Push and check#

Finally use git to add and push the modifications we did earlier.

To check all went done, go your Gitlab project, navigate to CI/CD > Pipelines and view jobs and stages details.

Bonus and reference#

My reference is Deploying a Vue.js app to Netlify using GitLab's CI/CD pipeline by Lawrence Braun, you can also check adding a staging preview section from this article.

Share