Since the source code of my website is kept on Github, using Github Actions to automate building and deploying my website seems to be a natural choice. Plus, it’s relatively simple to setup.
Step 1: Create the Workflow YAML
I’m using Hugo and Github provides a pretty good template for Hugo so it’s a good start. The only problem is that the template helps you deploy the website to Github Pages, but I need to deploy to my own server.
|
|
Here is the main steps of the workflow:
branches: ["master"]
defines the condition to trigger the workflow: a push event onto themaster
branch.- In
jobs
defines only one job:build-and-deploy
which will generate static website and deploy it to the server. Most configs and steps were provided in the template except:Get short SHA
will be used to name the folder uploaded to the serverDeploy to mywebsite.com
- Use the SSH private key to login to the server
- Use
rsync
to recursively sync generated static website to the server - Create symbolic link to the website root directory
- Remove previous uploads that are more than 180 days old
Why use one job to build and deploy
Instead of using a build job and a deployment job? Because that will require me to upload the generated static website to somewhere (for example, Github Pages) once the build is done, and then download it when the deployment job starts. I feel it’s not necessary for this simple project.
Step 2: Prepare User
An user “deployer” will be used to login to the server and does all the deployment work. I don’t want to use any existing users on the server so I can properly manage its permission and capability.
- Create the “deployer” user as I used in the workflow yaml, and create SSH folder
|
|
- Generate SSH keys for the user on the local computer
|
|
Don’t provide any passphrase. Otherwise it needs to be entered during the workflow. Two files will be generated under ~/.ssh
:
github_actions_deployer
: private keygithub_actions_deployer.pub
: public key
- Copy the content of the public key into
/home/deployer/.ssh/authorized_keys
- On Github repository, go to “Settings” and in “Secrets and variables”, create a Repository Secret named
MYWEBSITE_COM_KEY
for Actions, with the content of private key - Add the user to the group that owns
/var/www
directory
|
|
That’s it.