[recipe, sysadmin]: How to deploy a hugo-powered static website to a webserver with GIT
This website is powered by Hugo, an open-source static website generator written in Go. I can write pages and posts in Markdown and then generate some static .html pages to upload to a webserver.
For this project, as I usually do, I push every change to a self-hosted GIT server with Gogs (another open-source, golang written GIT server), so why not use webhooks to automate the deployment?
Gogs, as GitHub, GitLab and other well-known services provides webhooks to notify other services of changes in a repository: they are basically HTTP callbacks triggered by some user-defined events such as a push or a pull request. Each time you, for instance, push to a repo, Gogs will send a HTTP POST payload to the webhook’s configured URL: the payload will contain the relevant event information.
To protect from unauthorized requests you could tell Gogs to send, in the header of the POST request, a X-Gogs-Signature
that contains the HMAC hex digest of the payload generated using the sha256
hash function and a secret as the HMAC key.
My event-chain is the following: I push the new content to the repo, Gogs trigger a webook that send a HTTP POST payload to a .php page in the webserver. The php-page pulls the repo to the server, generates the static website with hugo
and copies the newly generated public
directory to the document root of the webserver.
So, let’s see the practical part:
-
Add in the Gogs repository configuration an ssh Deploy Key, to pull the repo in the webserver. The deploy key will have read-only access. You can generate the ssh key with
ssh-keygen
but keep it password-less to make the pull completely automated. -
Clone the repo in the document root with
git clone user@git.server:repo /var/www/
-
Insert in your
.htaccess
file the secret like that:SetEnv GOGS_DEPLOY_SECRET y0uRs3cRetC0d3
-
Create a
deploy.php
page that will pull the repo, generate the website and deploy it when called. You can use the following script: