My spouse needed a professional online presence — a clean CV site at her own domain. I could have thrown it on GitHub Pages and been done in an afternoon, but I wanted to build a proper infrastructure-as-code stack: static hosting on AWS, custom email with full authentication (DKIM, DMARC, MTA-STS), DNS on Cloudflare, and everything managed with OpenTofu.

If you just need a simple site, GitHub Pages is the pragmatic choice. But if you want a real-world example of wiring up AWS + Cloudflare + email security as code — read on.

Here’s how it all fits together.

                ┌─────────────────────┐
                │   Cloudflare DNS    │
                │   jancekova.com     │
                └─────────┬───────────┘
                          │
          ┌───────────────┼───────────────┐
          │               │               │
          ▼               ▼               ▼
    ┌──────────┐   ┌──────────┐   ┌──────────────┐
    │CloudFront│   │  Email   │   │  Email       │
    │  (CDN)   │   │ Routing  │   │  SES (SMTP)  │
    └────┬─────┘   │(inbound) │   │  (outbound)  │
         │         └──────────┘   └──────────────┘
         ▼
    ┌──────────┐
    │    S3    │
    │ (static) │
    └──────────┘

The Hugo Site

I chose Hugo for the site itself. It’s fast, generates pure static HTML, and is perfect for a single-page CV. The site uses a customized resume theme with sections for experience, education, skills, and contact info — all driven from hugo.toml.

Building and previewing locally is straightforward:

hugo server    # dev preview at localhost:1313
hugo --minify  # production build to public/

Infrastructure Overview

The infrastructure lives in a separate repo (jancekova.com-env) and is entirely managed with OpenTofu. Here’s what it provisions:

  • AWS S3 — private bucket for the static site files
  • AWS CloudFront — CDN with Origin Access Control (OAC)
  • AWS ACM — TLS certificate, DNS-validated via Cloudflare
  • AWS SES — outbound email with DKIM for Gmail “Send as”
  • Cloudflare — DNS, DNSSEC, Email Routing
  • S3 remote state — with native lockfile locking (no DynamoDB needed anymore)

I used Anton Babenko’s Terraform AWS modules for S3 and CloudFront where possible, and raw resources where the modules didn’t fit (ACM with Cloudflare validation, SES).

Static Hosting: S3 + CloudFront + OAC

The S3 bucket is completely private — no public access, no website hosting enabled. CloudFront accesses it via Origin Access Control (OAC), the modern replacement for Origin Access Identity (OAI). Most tutorials still show OAI — don’t use it for new projects.

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "~> 5.0"

  bucket        = "jancekova.com"
  force_destroy = true

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

The S3 bucket policy grants CloudFront access via the OAC. Note this is a separate resource from the module — putting the policy inside the module would create a circular dependency since it references the CloudFront distribution ARN:

resource "aws_s3_bucket_policy" "cloudfront_access" {
  bucket = module.s3_bucket.s3_bucket_id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Action    = "s3:GetObject"
      Resource  = "${module.s3_bucket.s3_bucket_arn}/*"
      Principal = { Service = "cloudfront.amazonaws.com" }
      Condition = {
        StringEquals = {
          "AWS:SourceArn" = module.cloudfront.cloudfront_distribution_arn
        }
      }
    }]
  })
}

The CloudFront distribution uses Babenko’s module. A few things worth noting:

  • OAC is configured inline — in module v6 you just pass the origin_access_control map (with signing_behavior = "always") and reference it from the origin via origin_access_control_key
  • Custom error response maps 403→404 — S3 returns 403 (not 404) for missing objects when using OAC, so you need this mapping or your visitors will see “Access Denied” instead of a proper 404 page. And make sure your Hugo site actually ships a 404.html (a layouts/404.html template) — I initially forgot, and the mapping alone still served the raw S3 AccessDenied XML
  • Cache policy uses the AWS-managed CachingOptimized policy ID instead of legacy forwarded_values
  • TLS — TLSv1.2_2025 security policy (the module’s new default) with a stricter cipher list
module "cloudfront" {
  source  = "terraform-aws-modules/cloudfront/aws"
  version = "~> 6.0"

  aliases = [
    "jancekova.com",
    "www.jancekova.com",
    "mta-sts.jancekova.com",
    "veronikajancekova.com",
    "www.veronikajancekova.com",
  ]
  comment             = "jancekova.com"
  enabled             = true
  is_ipv6_enabled     = true
  price_class         = "PriceClass_100"
  default_root_object = "index.html"

  # S3 returns 403 for missing objects with OAC — map to 404
  custom_error_response = [
    {
      error_code            = 403
      response_code         = 404
      response_page_path    = "/404.html"
      error_caching_min_ttl = 60
    }
  ]

  origin_access_control = {
    s3_oac = {
      description      = "CloudFront access to S3"
      origin_type      = "s3"
      signing_behavior = "always"
      signing_protocol = "sigv4"
    }
  }

  origin = {
    s3_origin = {
      domain_name               = module.s3_bucket.s3_bucket_bucket_regional_domain_name
      origin_access_control_key = "s3_oac"
    }
  }

  default_cache_behavior = {
    target_origin_id       = "s3_origin"
    viewer_protocol_policy = "redirect-to-https"
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]
    compress               = true
    cache_policy_id        = "658327ea-f89d-4fab-a63d-7e88639e58f6" # Managed-CachingOptimized

    function_association = {
      viewer-request = {
        function_arn = aws_cloudfront_function.url_rewrite.arn
      }
    }
  }

  viewer_certificate = {
    acm_certificate_arn      = aws_acm_certificate_validation.jancekova.certificate_arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = "TLSv1.2_2025"
  }
}

The CloudFront Function

A single CloudFront Function handles three responsibilities:

  1. MTA-STS policy — serves the email security policy directly (no extra S3 bucket needed)
  2. Domain redirects — 301 redirects from www.jancekova.com and veronikajancekova.com to the apex
  3. Hugo URL rewrite — converts /about/ to /about/index.html for Hugo’s pretty URLs
function handler(event) {
  var request = event.request;
  var host = request.headers.host.value;

  // MTA-STS policy
  if (host === 'mta-sts.jancekova.com') {
    if (request.uri === '/.well-known/mta-sts.txt') {
      return {
        statusCode: 200,
        statusDescription: 'OK',
        headers: { 'content-type': { value: 'text/plain' } },
        body: 'version: STSv1\nmode: enforce\nmx: route1.mx.cloudflare.net\nmx: route2.mx.cloudflare.net\nmx: route3.mx.cloudflare.net\nmax_age: 604800\n'
      };
    }
    return { statusCode: 404, statusDescription: 'Not Found' };
  }

  // Redirect every other host (www, veronikajancekova.com, *.cloudfront.net) to apex
  if (host !== 'jancekova.com') {
    return {
      statusCode: 301,
      statusDescription: 'Moved Permanently',
      headers: { location: { value: 'https://jancekova.com' + request.uri } }
    };
  }

  // Hugo index.html rewrite
  if (request.uri.endsWith('/')) {
    request.uri += 'index.html';
  } else if (!request.uri.includes('.')) {
    request.uri += '/index.html';
  }

  return request;
}

The redirect uses host !== 'jancekova.com' rather than a list of hostnames: CloudFront only accepts requests for the configured aliases anyway, so anything that isn’t the apex should be redirected — including direct hits on the *.cloudfront.net domain, which would otherwise serve a duplicate copy of the site.

Serving the MTA-STS policy from a CloudFront Function saved me from deploying a separate S3 bucket and CloudFront distribution for a 200-byte text file.

ACM Certificate with Cloudflare DNS Validation

ACM certificates are free, but they require DNS validation. When your DNS is on Cloudflare (not Route 53), you need to create the validation records cross-provider. This is straightforward for a single domain, but gets interesting when your cert covers multiple zones.

My cert covers five SANs across two Cloudflare zones (jancekova.com and veronikajancekova.com). The trick is using endswith() to route each validation record to the correct zone:

resource "aws_acm_certificate" "jancekova" {
  domain_name               = "jancekova.com"
  subject_alternative_names = [
    "www.jancekova.com",
    "mta-sts.jancekova.com",
    "veronikajancekova.com",
    "www.veronikajancekova.com"
  ]
  validation_method = "DNS"

  lifecycle {
    create_before_destroy = true
  }
}

# Validation records for jancekova.com zone
resource "cloudflare_dns_record" "acm_validation" {
  for_each = {
    for dvo in aws_acm_certificate.jancekova.domain_validation_options :
    dvo.domain_name => {
      name   = trimsuffix(dvo.resource_record_name, ".")
      record = trimsuffix(dvo.resource_record_value, ".")
      type   = dvo.resource_record_type
    } if endswith(dvo.domain_name, "jancekova.com")
      && !endswith(dvo.domain_name, "veronikajancekova.com")
  }

  zone_id = cloudflare_zone.jancekova.id
  name    = each.value.name
  type    = each.value.type
  content = each.value.record
  ttl     = 300
  proxied = false
}

# Validation records for veronikajancekova.com zone
resource "cloudflare_dns_record" "acm_validation_veronika" {
  for_each = {
    for dvo in aws_acm_certificate.jancekova.domain_validation_options :
    dvo.domain_name => {
      name   = trimsuffix(dvo.resource_record_name, ".")
      record = trimsuffix(dvo.resource_record_value, ".")
      type   = dvo.resource_record_type
    } if endswith(dvo.domain_name, "veronikajancekova.com")
  }

  zone_id = cloudflare_zone.veronikajancekova.id
  name    = each.value.name
  type    = each.value.type
  content = each.value.record
  ttl     = 300
  proxied = false
}

Two gotchas here:

  • The !endswith(dvo.domain_name, "veronikajancekova.com") guard is needed because veronikajancekova.com also ends with jancekova.com — without it, those records would land in the wrong zone.
  • The trimsuffix(..., ".") calls strip trailing dots from ACM’s FQDN values. Cloudflare doesn’t want them, and without trimming you’ll get phantom diffs on every tofu plan.

Email Setup

The email setup has two sides: inbound and outbound.

Inbound: Cloudflare Email Routing

Cloudflare Email Routing forwards veronika@jancekova.com to a personal Gmail account. It’s free, requires zero infrastructure, and is configured entirely in OpenTofu. It takes three resources: enabling Email Routing on the zone (Cloudflare then manages the MX records itself — don’t create them by hand), the destination address, and the routing rule:

# Enables Email Routing and its MX/SPF records on the zone
resource "cloudflare_email_routing_dns" "jancekova" {
  zone_id = cloudflare_zone.jancekova.id
}

# Destination must click a verification link before forwarding works
resource "cloudflare_email_routing_address" "gmail" {
  account_id = var.cflare_account_id
  email      = "destination@gmail.com"
}

resource "cloudflare_email_routing_rule" "veronika" {
  zone_id = cloudflare_zone.jancekova.id
  name    = "veronika to gmail"
  enabled = true

  matchers = [{ type = "literal", field = "to", value = "veronika@jancekova.com" }]
  actions  = [{ type = "forward", value = ["destination@gmail.com"] }]

  depends_on = [cloudflare_email_routing_dns.jancekova]
}

Outbound: AWS SES

For sending emails as veronika@jancekova.com from Gmail (via “Send mail as”), I set up AWS SES with a verified domain identity and DKIM signing. SES provides SMTP credentials that plug directly into Gmail’s settings.

The key advantage of SES over using Gmail’s own SMTP: proper DKIM alignment for the custom domain, which means DMARC can eventually be tightened to p=reject.

The setup has three parts: domain verification, DKIM signing, and an IAM user for SMTP credentials:

# Domain identity + verification
resource "aws_ses_domain_identity" "jancekova" {
  domain = "jancekova.com"
}

resource "cloudflare_dns_record" "ses_verification" {
  zone_id = cloudflare_zone.jancekova.id
  name    = "_amazonses.jancekova.com"
  type    = "TXT"
  content = aws_ses_domain_identity.jancekova.verification_token
  ttl     = 600
}

# DKIM — SES generates 3 tokens, each needs a CNAME record
resource "aws_ses_domain_dkim" "jancekova" {
  domain = aws_ses_domain_identity.jancekova.domain
}

resource "cloudflare_dns_record" "ses_dkim" {
  count   = 3
  zone_id = cloudflare_zone.jancekova.id
  name    = "${aws_ses_domain_dkim.jancekova.dkim_tokens[count.index]}._domainkey.jancekova.com"
  type    = "CNAME"
  content = "${aws_ses_domain_dkim.jancekova.dkim_tokens[count.index]}.dkim.amazonses.com"
  ttl     = 600
}

# IAM user for SMTP credentials
resource "aws_iam_user" "ses_smtp" {
  name = "ses-smtp-jancekova"
}

resource "aws_iam_user_policy" "ses_smtp" {
  name   = "ses-send"
  user   = aws_iam_user.ses_smtp.name
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect   = "Allow"
      Action   = "ses:SendRawEmail"
      Resource = "*"
    }]
  })
}

resource "aws_iam_access_key" "ses_smtp" {
  user = aws_iam_user.ses_smtp.name
}

The SMTP interface uses ses:SendRawEmail, so that’s the minimum action the policy needs. Resource = "*" lets the user send from any verified identity in the account; you can scope it down to the domain identity ARN (arn:aws:ses:us-east-1:<account>:identity/jancekova.com) if the account hosts other senders. If you see 554 Access denied from the SMTP endpoint, the IAM policy is what’s rejecting you — check the action, the ARN (region included), and any SCPs or permission boundaries.

The SMTP username and password are derived from the IAM access key. OpenTofu can output them as sensitive values:

output "ses_smtp_username" {
  value     = aws_iam_access_key.ses_smtp.id
  sensitive = true
}

output "ses_smtp_password" {
  value     = aws_iam_access_key.ses_smtp.ses_smtp_password_v4
  sensitive = true
}

Use tofu-kxc output -raw ses_smtp_password (see Secrets below) to retrieve them for Gmail’s “Send mail as” SMTP configuration.

DNS Records for Email Security

The full email security stack is managed in OpenTofu:

# SPF — authorize Cloudflare (inbound) and SES (outbound)
resource "cloudflare_dns_record" "spf" {
  zone_id = cloudflare_zone.jancekova.id
  name    = "jancekova.com"
  type    = "TXT"
  content = "v=spf1 include:_spf.mx.cloudflare.net include:amazonses.com ~all"
  ttl     = 600
}

# DMARC
resource "cloudflare_dns_record" "dmarc" {
  zone_id = cloudflare_zone.jancekova.id
  name    = "_dmarc.jancekova.com"
  type    = "TXT"
  content = "v=DMARC1; p=none; rua=mailto:veronika@jancekova.com"
  ttl     = 600
}

# MTA-STS — tells sending servers to require TLS
resource "cloudflare_dns_record" "mta_sts_txt" {
  zone_id = cloudflare_zone.jancekova.id
  name    = "_mta-sts.jancekova.com"
  type    = "TXT"
  content = "v=STSv1; id=20260328"
  ttl     = 600
}

Together with the DKIM CNAMEs from SES, this gives you a complete email authentication stack.

You’ll often see TLSRPT (_smtp._tls TXT record) recommended alongside MTA-STS. I added it initially and removed it a day later: it’s purely a reporting mechanism — it doesn’t change how mail is delivered or protected — and the daily JSON reports from Google and Microsoft would just land in a personal inbox nobody reads. For a business domain with someone actually monitoring mail flow, keep it. Start with p=none for DMARC to monitor, then tighten to p=quarantine or p=reject once you’ve confirmed everything passes.

Remote State

OpenTofu state is stored in S3 with versioning and KMS encryption. Locking uses the S3 backend’s native lockfile (use_lockfile, available since OpenTofu 1.10) — a .tflock object next to the state — so there’s no DynamoDB table to provision anymore:

terraform {
  required_version = ">= 1.13.0"

  backend "s3" {
    bucket       = "jancekova.com-env"
    key          = "terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

If you’re migrating an existing setup off DynamoDB, switch the backend config, run tofu init -reconfigure, and then remove the table.

Encrypting the state itself

S3 server-side encryption protects the state at rest, but anyone who can read the bucket still sees everything in plain text — including the SES SMTP password from the outputs above. OpenTofu (unlike Terraform) can encrypt state and plan files client-side:

terraform {
  encryption {
    key_provider "pbkdf2" "kxc" {
      passphrase = var.state_passphrase # sensitive variable, injected from KeePassXC
    }

    method "aes_gcm" "kxc" {
      keys = key_provider.pbkdf2.kxc
    }

    state {
      method   = method.aes_gcm.kxc
      enforced = true
    }

    plan {
      method   = method.aes_gcm.kxc
      enforced = true
    }
  }
}

For an existing unencrypted state, add method "unencrypted" "migrate" {} as a fallback in both blocks, run tofu apply once, then remove the fallback and set enforced = true. Two warnings: lose the passphrase and you lose the state, and the bucket’s versioning keeps the old unencrypted versions around — delete them after migrating. A KMS key provider (aws_kms) is the alternative if you’d rather not manage a passphrase; it costs $1/month per key. Pick the key provider and method names carefully (I use kxc) — they’re stored in the encrypted metadata, and renaming them later needs another fallback migration.

Secrets: KeePassXC, not files

My first version read the Cloudflare token with file("~/.credentials/cloudflare") — a plaintext secret on disk, and a config that breaks on any machine without that exact file. Now no secret is in the repo, in a file, or in the HCL. The Cloudflare provider block is empty and takes the token from CLOUDFLARE_API_TOKEN; the state passphrase is an ordinary sensitive variable:

# Token only from the environment (CLOUDFLARE_API_TOKEN).
provider "cloudflare" {}

variable "state_passphrase" {
  type      = string
  sensitive = true
}

Both values come from KeePassXC through a small wrapper, tofu-kxc, shared by all my infra repos. Each repo commits a kxc.env that lists only entry names, never values:

# kxc.env — KeePassXC entries (https://<host>) exported by tofu-kxc
CLOUDFLARE_API_TOKEN=cloudflare.kxc
TF_VAR_state_passphrase=tofu-state.kxc

The wrapper looks each entry up by its URL field in the running, unlocked KeePassXC (via git-credential-keepassxc and the browser-integration socket, so there’s no extra password prompt), exports it, and execs tofu. The core of it:

while read -r assign field _; do
  [[ -z "$assign" || "$assign" == \#* ]] && continue
  [[ "$assign" =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.+)$ ]]
  value=$(printf 'protocol=https\nhost=%s\n\n' "${BASH_REMATCH[2]}" \
    | git-credential-keepassxc --unlock 60 get | sed -n "s/^${field:-password}=//p")
  export "${BASH_REMATCH[1]}=$value"
done < kxc.env
exec tofu "$@"

Day to day it’s a drop-in replacement for tofu, always with a saved, reviewed plan:

tofu-kxc init -input=false
tofu-kxc plan -input=false -out=p.tfplan
tofu-kxc apply p.tfplan && rm p.tfplan

Secrets live only in the process environment for the duration of the run — and since the state and plan are encrypted, the values tofu has to persist (like the SMTP password) aren’t readable at rest either.

Protecting what’s painful to recreate

Destroying the Cloudflare zone breaks the DNSSEC chain at the registrar, and replacing the SMTP access key silently breaks Gmail’s “Send mail as”. OpenTofu 1.12+ allows variables in prevent_destroy, so these resources are protected by default but can still be torn down deliberately:

resource "cloudflare_zone" "jancekova" {
  # ...
  lifecycle {
    prevent_destroy = var.protect_critical # default true; `tofu destroy -var protect_critical=false`
  }
}

Deploying

A simple shell script in the Hugo repo handles the full deploy:

#!/usr/bin/env bash
set -euo pipefail

PROFILE="chrismazanec"
BUCKET="jancekova.com"
DISTRIBUTION_ID="EXXXXXXXXXXXXX"

cd "$(dirname "$0")"
hugo --minify
aws s3 sync public/ "s3://${BUCKET}/" --delete --profile "$PROFILE"
aws cloudfront create-invalidation \
  --distribution-id "$DISTRIBUTION_ID" \
  --paths "/*" --profile "$PROFILE"

Build, sync, invalidate cache. Done in under a minute.

Cost

The entire setup runs on free tiers or near-zero costs:

  • S3 — cents for a static site
  • CloudFront — 1 TB/month free tier
  • ACM — free
  • SES — about $0.10–0.16 per 1,000 emails; for a personal mailbox that’s fractions of a cent per month (new AWS accounts no longer get a separate SES free tier, just general Free Tier credits)
  • Cloudflare — free plan (DNS, Email Routing, DNSSEC)

Would I Do This Again?

For a simple CV site, GitHub Pages would be the pragmatic choice — it eliminates ACM, S3, and CloudFront entirely. Push and deploy. The trade-off is less control over caching and no built-in place for MTA-STS, but for most personal sites that’s fine.

I went with the full AWS stack because I wanted a real-world example of infrastructure-as-code with proper email security. It’s been running maintenance-free since day one, and the entire setup costs essentially nothing.

Comments

Loading comments…

    Leave a comment

    Comments are moderated and appear after approval. Only your name and comment are stored.