Using Hugo and AWS to build a fast, static, easily managed and deployed website.
Tags: aws, hugo, devops, webdev
Published: 2019-01-21 10:51:22



---
title: Using Hugo and AWS to build a fast, static, easily managed and deployed website.
Description: I wanted to create something that aligned with and demonstrated some of the key tenets of cloud technology - scalability, resiliency, availability, and security, and was designed for the cloud, not simply in the cloud.
tags: AWS, Hugo, DevOps, webdev, 
published: true
---


Most of my websites are built using Wordpress on Linux in AWS, using EC2 for compute, S3 for storage and Aurora for the data layer. Take a look at <a href="http://sono.life" target="_blank" rel="noopener">sono.life </a>as an example.

For this site, I wanted to build something that aligned with, and demonstrated some of the <a href="https://hackernoon.com/principles-and-practices-of-cloud-applications-4a8ef32cab36">key tenets of cloud technology</a> - that is: scalability, resiliency, availability, and security, and was designed <em><strong>for</strong></em> the cloud, not simply <strong><em>in</em></strong> the cloud.

I chose technologies that were cloud native, were as fast as possible, easily managed, version controlled, quickly deployed, and presented over TLS. I opted for <a href="https://gohugo.io/" target="_blank" rel="noopener">Hugo</a>, a super-fast static website generator that is managed from the command line. It's used by organisations such as <a href="https://letsencrypt.org/">Let's Encrypt</a> to build super fast, secure, reliable and scalable websites. The rest of my choices are listed below. Wherever possible, I've used the native AWS solution.
<ul>
 	<li>Framework: <a href="https://gohugo.io/">Hugo</a></li>
 	<li>Source control: <a href="https://github.com/tom-geraghty">Git/Github</a></li>
 	<li>DNS: <a href="https://aws.amazon.com/route53/">AWS Route53</a></li>
 	<li>Deployment: <a href="https://aws.amazon.com/cli/">AWS cli</a> - boto/python</li>
 	<li>Scripting: <a href="https://www.npmjs.com/">NPM</a></li>
 	<li>Continuous Integration: <a href="https://circleci.com/blog/automate-your-static-site-deployment-with-circleci/">Circle CI</a></li>
 	<li>SSL: <a href="https://aws.amazon.com/certificate-manager/">AWS Certificate Manager</a></li>
 	<li>Storage: <a href="https://aws.amazon.com/s3/">AWS S3</a></li>
 	<li>Presentation layer: <a href="https://aws.amazon.com/cloudfront/">AWS CloudFront</a> distribution</li>
 	<li>Analytics and tracking: <a href="https://analytics.google.com/analytics/web/">Google Analytics</a></li>
 	<li>Commenting: <a href="https://disqus.com/">Disqus</a></li>
</ul>
<img class="aligncenter wp-image-880 size-full" src="https://d1dy13pz7fy27z.cloudfront.net/images/speedtest.png" alt="" width="1876" height="226" />

The whole site <a href="https://www.webpagetest.org/result/190116_1W_9c9428be930a0cd9e0d590fce1f396b9/">loads in less than half a second</a>, and there are still improvements to be made. It may not be pretty, but it's fast. Below is a walk through and notes that should help you build your own Hugo site in AWS. The notes assume that you know your way around the command line, that you have an AWS account and have a basic understanding of the services involved in the build. I think I've covered all the steps, but if you try to follow this and spot a missing step, <a href="https://cv.tomgeraghty.co.uk/contact/">let me know</a>.

<strong>Notes on Build - Test - Deploy:</strong>

Hugo was installed via <a href="https://brew.sh/">HomeBrew </a>to build the site. If you haven't installed Homebrew yet, just do it. Fetch by running:
<pre>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"</pre>
<div class="col-1">Then install Hugo:</div>
<pre>brew install hugo</pre>
One of the things I love about Hugo is the ability to make rapid, on-the-fly changes to the site and see the result instantly, running the <a href="https://gohugo.io/commands/hugo_server/">Hugo server</a> locally.
<pre>hugo server -w -D</pre>
The option -D includes drafts in the output, whilst -w watches the filesystem for changes, so you don't need to rebuild with every small change, or even refresh in the browser.

To create content, simply run
<pre>hugo new $postname.md</pre>
Then create and edit your content, QA with the local Hugo server, and build the site when you're happy:
<pre>hugo -v
</pre>
V for verbose, obvs.

You'll need to install the AWS CLI, if you haven't already.
<pre>brew install awscli</pre>
Check it worked:
<pre>aws --version</pre>
Then set it up with your AWS IAM credentials:
<pre>aws configure
AWS Access Key ID [None]: &lt;your access key&gt;
AWS Secret Access Key [None]: &lt;your secret key&gt;
Default region name [None]: &lt;your region name&gt;
Default output format [None]: ENTER</pre>
You don't need to use R53 for DNS, but it doesn't cost much and it will make your life a lot easier. Plus you can use funky features like routing policies and target health evaluation (though not when using Cloudfront distributions as a target).

Create your record set in R53. You'll change the target to a Cloudfront distribution later on. Create the below json file with your config.
<div class="aws-code parbase section text">
<pre>{
            "Comment": "CREATE/DELETE/UPSERT a record ",
            "Changes": [{
            "Action": "CREATE",
                        "ResourceRecordSet": {
                                    "Name": "a.example.com",
                                    "Type": "A",
                                    "TTL": 300,
                                 "ResourceRecords": [{ "Value": "4.4.4.4"}]
}}]
}</pre>
</div>
<div class="aws-text-box section">
<div class=" ">And run:</div>
</div>
<pre>aws route53 change-resource-record-sets --hosted-zone-id ZXXXXXXXXXX --change-batch file://sample.json</pre>
Create a bucket. Your bucket name needs to match the hostname of your site, unless you want to get really hacky.
<div class="highlight-python">
<pre>aws s3 mb s3://my.website.com --region eu-west-1</pre>
</div>
If you're using Cloudfront, you'll need to specify permissions to allow the Cloudfront service to pull from S3. Or, if you're straight up hosting from S3, ensure you allow the correct permissions. There are many variations on how to do this - the AWS recommended way would be to set up an <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html#private-content-creating-oai">Origin Access Identity</a>, but that won't work if you're using Hugo and need to use a custom origin for Cloudfront (see below). If you don't particularly mind if visitors can access S3 assets if they try to, your S3 policy can be as below:
<pre>{
  <span class="hljs-attr">"Version"</span>:<span class="hljs-string">"2012-10-17"</span>,
  <span class="hljs-attr">"Statement"</span>:[{
	<span class="hljs-attr">"Sid"</span>:<span class="hljs-string">"PublicReadGetObject"</span>,
        <span class="hljs-attr">"Effect"</span>:<span class="hljs-string">"Allow"</span>,
	  <span class="hljs-attr">"Principal"</span>: <span class="hljs-string">"*"</span>,
      <span class="hljs-attr">"Action"</span>:[<span class="hljs-string">"s3:GetObject"</span>],
      <span class="hljs-attr">"Resource"</span>:[<span class="hljs-string">"arn:aws:s3:::example-bucket/*"</span>
      ]
    }
  ]
}</pre>
Request your SSL certificate at this time too:
<pre>aws acm request-certificate --domain-name $YOUR_DOMAIN --subject-alternative-names "www.$YOUR_DOMAIN" <code class="language-bash hljs">
</code></pre>
ACM will automatically renew your cert for you when it expires, so you can sleep easy at night without worrying about SSL certs expiring. That stuff you did last summer at bandcamp will still keep you awake though.

Note: Regards Custom SSL client support, make sure to select ONLY SNI. Supporting old steam driven browsers on WinXP will cost you $600, and I don't think you want that.

The only way to use https with S3 is to stick a Cloudfront distribution in front of it, and by doing this you get the added bonus of a super fast CDN with over 150 edge locations worldwide.

Create your Cloudfront distribution with a json config file, or straight through the cli.
<div class="highlight-python">
<pre>aws cloudfront create-distribution --distribution-config file://distconfig.json</pre>
</div>
Check out the <a href="https://docs.aws.amazon.com/cli/latest/reference/cloudfront/create-distribution.html">AWS documentation</a> for details on how to create your config file.

Apply your certificate to the CF distribution too, in order to serve traffic over https. You can choose to allow port 80 or redirect all requests to 443. Choose "custom" certificate to select your cert, otherwise Cloudfront will use the Amazon default one, and visitors will see a certificate mismatch when browsing to the site.

When configuring my Cloudfront distribution, I hit a few issues. First of all, it's not possible to use the standard AWS S3 origin. You must use a custom origin (specifying the region of the S3 bucket as below in order for pretty URLs and CSS references in Hugo to work properly. I.e.
<pre>cv.tomgeraghty.co.uk.s3-website-eu-west-1.amazonaws.com 
</pre>
instead of
<pre>cv.tomgeraghty.co.uk.s3.amazonaws.com</pre>
Also, make sure to specify the default root object in the CF distribution as index.html.

Now that your CF distribution is ready, anything in your S3 bucket will be cached to the CF CDN. Once the status of your distribution is "deployed", it's ready to go. It might take a little while at first setup, but don't worry. Go and make a cup of tea.

Now, point your R53 record at either your S3 bucket or your Cloudfront disti. You can do this via the cli, but doing it via the console means you can check to see if your target appears in the list of alias targets. Simply select "A - IPv4 address" as the target type, and choose your alias target (CF or S3) in the drop down menu.

Stick an index.html file in the root of your bucket, and carry out an end-to-end test by browsing to your site.

<strong>Build - Test - Deploy</strong>

Now you have a functioning Hugo site running locally, S3, R53, TLS, and Cloudfront, you're ready to stick it all up on the internet.

Git push if you're using Git, and deploy the public content via whichever method you choose. In my case, to the S3 bucket created earlier:
<pre class="p1"><span class="s1">aws s3 cp public s3://$bucketname --recursive</span></pre>
The recursive switch ensures the subfolders and content will be copied too.

Crucially, because I'm hosting via Cloudfront, a new deploy means the old Cloudfront content will be out of date until it expires, so alongside every deploy, an invalidation is required to trigger a new fetch from the S3 origin:
<pre class="p1"><span class="s1">aws cloudfront create-invalidation --distribution-id $cloudfrontID<span class="Apple-converted-space">  </span>--paths /\*</span></pre>
It's not the cleanest way of doing it, but it's surprisingly quick to refresh the CDN cache so it's ok for now.

Time to choose a theme and modify the hugo config file. This is how you define how your Hugo site works.

I used the "Hermit" theme:
<pre><span style="font-size: 1rem;">git clone https://github.com/Track3/hermit.git themes/hermit</span></pre>
<span style="font-size: 1rem;">But you could choose any theme you like from https://themes.gohugo.io/</span>

Modify the important elements of the config.toml file:
<pre>baseURL = "$https://your-website-url"
languageCode = "en-us"
defaultContentLanguage = "en"
title = "$your-site-title"
theme = "$your-theme"
googleAnalytics = "$your-GA-UA-code"
disqusShortname = "$yourdiscussshortname"</pre>
Get used to running a deploy:
<pre>hugo -v</pre>
<pre class="p1"><span class="s1">aws s3 cp public s3://your-site-name --recursive
</span></pre>
<pre class="p1"><span class="s1">aws cloudfront create-invalidation --distribution-id XXXXXXXXXX<span class="Apple-converted-space">  </span>--paths /\*</span></pre>
Or, to save time, set up npm to handle your build and deploy. Install node and NPM if you haven't already (I'm assuming you're going to use Homebrew again.
<pre>$ brew install node</pre>
Then check node and npm are installed by checking the version:
<pre>npm -v</pre>
and
<pre>node -v</pre>
All good? Carry on then:
<pre>npm init</pre>
Create some handy scripts:
<pre>{
	"name": "hugobuild",
	"config": {
		"LASTVERSION": "0.1"
	},
	
	"version": "1.0.0",
	"description": "hugo build and deploy",
	"dependencies": {
		"dotenv": "^6.2.0"


	},

	"devDependencies": {},
	"scripts": {
		"testvariable": "echo $npm_package_config_LASTVERSION",
		"test": "echo 'I like you Clarence. Always have. Always will.'",
		"server": "hugo server -w -D -v",
		"build": "hugo -v",
		"deploy": "aws s3 cp public s3://<bucketname> --recursive && aws cloudfront create-invalidation --distribution-id <distributionID> --paths '/*'"
	},
	"author": "Tom Geraghty",
	"license": "ISC"
}
		</pre>
Then, running:
<pre>npm run server</pre>
will launch a local server running at http://localhost:1313

Then:
<pre>npm run build</pre>
will build your site ready for deployment.

And:
<pre>npm deploy</pre>
will upload content to S3 and tell Cloudfront to invalidate old content and fetch the new stuff.

Now you can start adding content, and making stuff. Or, if you're like me and prefer to fiddle, you can begin to implement Circle CI and other tools.

<strong>Notes: some things you might not find in other Hugo documentation:</strong>

When configuring the SSL cert - just wait, be patient for it to load. Reload the page a few times even. This gets me every time. The AWS Certificate manager service can be very slow to update.

Take a look at custom behaviours in your CF distribution for error pages so they’re cached for less time. You don't want 404's being displayed for content that's actually present.

<strong>Finally, some things I'm still working on:</strong>

Cloudfront fetches content from S3 over port 80, not 443, so this wouldn’t be suitable for secure applications because it’s not end-to-end encrypted. I'm trying to think of a way around this.

I'm implementing <a href="https://circleci.com/">Circle CI</a>, just for kicks really.

Finally, invalidations. As above, if you don't invalidate your CF disti after deployment, old content will be served until the cache expires. But invalidations are inefficient and ultimately cost (slightly) more. The solution is to implement versioned object names, though I'm yet to find a solution for this that doesn't destroy other Hugo functionality. If you know of a clean way of doing it, <a href="https://cv.tomgeraghty.co.uk/contact/">please tell me</a> :)

&nbsp;