Using github actions with hugo deploy to push to S3
Rebuilding the website and going into the AWS console to upload the new content was not something i enjoyed. Turns out hugo (which the site runs oun) has a deploy command which can be used with Github actions - meaning that when i push content to my github repo, it will run an action that rebuilds my website, pushes to S3 and invalidates the cache in CloudFront.
Making the action run on push
To make the action run on push to main branch, i created
.github/workflows/main.yml
file inside the git repo and added:
1name: Build & Deploy hugo website
2
3on:
4 push:
5 branches: [ main ]
So now when i push to main, the action runs.
Configuring hugo to allow deployment
To allow hugo to use the deploy command, we need to configure it inside the hugo config file. Simply added:
1[deployment]
2[[deployment.targets]]
3name = "{{ WEBSITE-NAME }}"
4URL = "s3://{{ BUCKET-NAME }}region=eu-region-X"
5cloudFrontDistributionID = "ABCDEFG1234567"
Now the hugo deploy
works as it should.
Creating the action jobs
First, we need an checkout action so our workflow can access our repo
1jobs:
2 deploy:
3 runs-on: ubuntu-18.04
4 steps:
5 - uses: actions/checkout@v2
6 with:
7 submodules: true # Fetch hugo themes
Then we set up the hugo-action itself
1 # Set up hugo
2 - name: Setup Hugo
3 uses: peaceiris/actions-hugo@v2
4 with:
5 hugo-version: 'latest'
And add the jobs which builds and deploy the actual site. The deploy command also comes with invalidateCDN
flag, which is convenient. Environment variables used to specify our (iam) user which will upload S3 objects and invalidate CDN.
1 - name: Build hugo with --minify
2 run: hugo --minify
3 - name: Deploy to S3
4 run: hugo deploy --force --maxDeletes -1 --invalidateCDN
5 env:
6 AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
7 AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
Setting up user credentials
Created a group and added following policies:
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Sid": "VisualEditor0",
6 "Effect": "Allow",
7 "Action": [
8 "s3:PutObject",
9 "s3:GetObjectAcl",
10 "s3:ListBucket",
11 "s3:GetBucketLocation",
12 "s3:PutObjectAcl"
13 ],
14 "Resource": [
15 "arn:aws:s3:::[BUCKET-ID]/*",
16 "arn:aws:s3:::[BUCKET-ID]"
17 ]
18 }
19 ]
20}
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Sid": "VisualEditor0",
6 "Effect": "Allow",
7 "Action": "cloudfront:CreateInvalidation",
8 "Resource": "arn:aws:cloudfront:[ACCOUNT-ID]:distribution/[DIST-ID]"
9 }
10 ]
Then created a user with programmatic access and added the access key ID and secret access key to github secrets, which the github action can access.
Summary
Created github action which builds and deploy the hugo site. Created a user with minimum access (principle of least privilege). Happy with the result, now i don’t have to fiddle around in the AWS console.