When creating static websites with your preferred generator, it’s sometimes hard to keep track of and review changes as they come in through your source code management system.
One possible alleviation of this process are preview deploys to a static hosting provider such as Netlify, now.sh, Github Pages or what have you. I will be referring to Netlify in this post, but feel free to extrapolate to the provider of your choice.
If you follow a typical Git flow the changesets arrive in the form of pull (or merge) requests, and the review process can be greatly accelerated by preparing preview deploys to the assigned reviewers.
Netlify does that out of the box when you employ one of the big source forges, but when you’re running your own, say, Gitlab instance, you’re out on your own.
Below I lay out a simple approach on how you can achieve the same using Gitlab CI and a few calls to the Gitlab API, the static site generator used is Gatsby.
Here is a step-by-step instruction.
Get a personal access token from your self hosted Gitlab instance. You’ll need this to make changes to your merge requests.
Sign up for a free Netlify account if you don’t already have one.
-
Create a site on Netlify. Because you cannot connect it via Git, the only way to to this, is to upload a static site folder (in the case of Gatsby,
/public
). -
Go to Site > Site Settings and take a note of your site id.
-
Go to User Settings > Applications and create a new access token.
-
In your Gitlab project, go to Settings > CI/CD and enter these as variables
PRIVATE_ACCESS_TOKEN
,NETLIFY_SITE_ID
andNETLIFY_AUTH_TOKEN
Below is a sample
.gitlab-ci.yml
file. The hidden champion in this case is the awesome jq tool 🌟
Enjoy!
image: node:10-buster
stages:
- preview
preview:
stage: preview
only:
- merge_requests
script:
- apt-get update && apt-get install -y jq curl
- npm i
- npm run build
- npm i -g netlify-cli
- NETLIFY_JSON=$(netlify deploy --site $NETLIFY_SITE_ID --auth $NETLIFY_AUTH_TOKEN --json)
- DEPLOY_URL=$(echo $NETLIFY_JSON | jq -r ".deploy_url")
- MR_DESCRIPTION=$(curl "https://my-gitlab-instance/api/v4/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID?private_token=$PRIVATE_ACCESS_TOKEN" | jq -r ".description")
- MR_DESCRIPTION="$MR_DESCRIPTION\n\n[$DEPLOY_URL]($DEPLOY_URL)"
- 'curl -X PUT -H "Content-Type: application/json" -d "{\"description\":\"$MR_DESCRIPTION\"}" "https://my-gitlab-instance/api/v4/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID?private_token=$PRIVATE_ACCESS_TOKEN"'
Top comments (0)