Terraform module for configuring WordPress with CloudFront

In this post, I’m going to cover how to use the Terraform CloudFront WordPress module to add CDN support for your WordPress website.

Pre-requiste:

  1. Custom SSL (I recommand generating certificates using ACL).
  2. Access to the DNS settings of your domain.
  3. Access to the WordPress admin (we might need to write few PHP functions).

Step 1. Add the Terraform WordPress CloudFront module

module "cloudfront_wordpress" {
   source  = "soroushatarod/cloudfront-wordpress/aws"
   version = "1.0.1"
   cnames = ["www.example.com"]
   domain_name = "example.com"
   origin_id = "E22XRTe7wQ72"
   enabled = true
   origin_protocol_policy = "http-only"
   acm_certificate_arn = "arn:aws:acm:us-east-1:20:certificate/9489-60"
   tags = {
     name = "production"
   }
}

 

Variable definitions

cnames the custom domain name which you want to update its DNS record
domain_name the website root domain name.
origin_id Unique identifer for the origin example: master_origin
enabled whether to enable the distribution or not.
origin_protocol_policy

If you want CloudFront to connect to your origin through HTTP set it “http-only” otherwise “https-only”.

The advantage of using “http-only” is that you don’t need to add SSL to your origin server.

acm_certificate_arn  The SSL certificate ARN (Amazon Resource Name). This can be found on the “Certificate Manager” dashboard.
 tags  custom tags to make it easy to manage the CloudFront

Step 2: Testing if the distribution works before making any DNS changes.

This is an important step. The last thing, we want is to update the DNS record and have a website downtime.

a) Run a dig command on the CloudFront Domain name

dig df7tznuwvmynn.cloudfront.net

b) pick any of the IP addresses, and create a record on your hosts file

/etc/hosts

www.example.com 54.192.32.130

c) Visit the www.example.com and try to login, logout and browse few pages. It should work fine.

Make sure the host record changes have been active by performing a ping command.

 

Step 3: Update DNS record for the cnames.

Now, that we are confident the CloudFront changes are working fine. We would need to update the DNS records. If you are using Route53 to manage the DNS record, you could simply create an alias pointing www.example.com to the CloudFront distribution otherwise, add the Cloudfront cname to the www.example.com.

If you view the Chrome Network tools, it should display Hit from CloudFront. If you are receiving Miss from CloudFront this could be because of the header status the WordPress website is sending back. To find out how to resolve the Miss From CloudFront view this post.