Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: A Static Website on Object Storage and a CDN with Pulumi

Build a complete static website stack with Pulumi: private bucket, CDN with origin access control, HTTPS certificate, DNS, cache headers and content-type upload planning, with testable logic.

In this project you will design a production-style static website: HTML, CSS and images served over HTTPS from a CDN, with the files stored in a private bucket that only the CDN can read. It touches everything from this chapter group: a component with a clean API, tags and policies, previews and a deployment pipeline.

You cannot deploy to a cloud from this site, so the Pulumi program is shown as read-only TypeScript. The pieces that are pure logic (content types, cache headers, invalidation decisions) are runnable stand-ins, because those are the parts that cause real-world bugs.

Architecture

flowchart LR
  U["Visitor"] --> DNS["DNS: www.example.com"]
  DNS --> CDN["CDN distribution (HTTPS, caching)"]
  CDN -- "origin access control" --> B[("Private bucket: site files")]
  Cert["TLS certificate"] -.-> CDN
  CI["CI pipeline: pulumi up + upload"] --> B
  CI -- "invalidate changed paths" --> CDN

The bucket is never public; the CDN signs its requests to the bucket.

Requirements:

  1. All traffic is HTTPS; HTTP redirects to HTTPS.
  2. The bucket blocks all public access.
  3. Fingerprinted assets (app.3f9a1c.js) are cached for a year; HTML is revalidated quickly.
  4. A deploy invalidates only what changed.
  5. Everything is tagged and previewed in PRs.

The Pulumi program (read-only)

TypeScript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

const config = new pulumi.Config();
const domain = config.require("domain");            // e.g. "www.example.com"
const zoneId = config.require("hostedZoneId");
const tags = { project: "site", environment: pulumi.getStack(), owner: "web" };

// Certificates for CloudFront must live in us-east-1.
const usEast = new aws.Provider("us-east-1", { region: "us-east-1" });

const bucket = new aws.s3.BucketV2("site", { tags });
new aws.s3.BucketPublicAccessBlock("site-block", {
  bucket: bucket.id,
  blockPublicAcls: true,
  blockPublicPolicy: true,
  ignorePublicAcls: true,
  restrictPublicBuckets: true,
});

const cert = new aws.acm.Certificate("site-cert", {
  domainName: domain,
  validationMethod: "DNS",
  tags,
}, { provider: usEast });

const validationRecord = new aws.route53.Record("site-cert-validation", {
  zoneId,
  name: cert.domainValidationOptions[0].resourceRecordName,
  type: cert.domainValidationOptions[0].resourceRecordType,
  records: [cert.domainValidationOptions[0].resourceRecordValue],
  ttl: 60,
});
const certValid = new aws.acm.CertificateValidation("site-cert-valid", {
  certificateArn: cert.arn,
  validationRecordFqdns: [validationRecord.fqdn],
}, { provider: usEast });

const oac = new aws.cloudfront.OriginAccessControl("site-oac", {
  originAccessControlOriginType: "s3",
  signingBehavior: "always",
  signingProtocol: "sigv4",
});

const cdn = new aws.cloudfront.Distribution("site-cdn", {
  enabled: true,
  aliases: [domain],
  defaultRootObject: "index.html",
  origins: [{
    originId: "s3",
    domainName: bucket.bucketRegionalDomainName,
    originAccessControlId: oac.id,
  }],
  defaultCacheBehavior: {
    targetOriginId: "s3",
    viewerProtocolPolicy: "redirect-to-https",
    allowedMethods: ["GET", "HEAD"],
    cachedMethods: ["GET", "HEAD"],
    compress: true,
    cachePolicyId: "658327ea-f89d-4fab-a63d-7e88639e58f6", // managed CachingOptimized policy
  },
  customErrorResponses: [{ errorCode: 404, responseCode: 404, responsePagePath: "/404.html" }],
  restrictions: { geoRestriction: { restrictionType: "none" } },
  viewerCertificate: { acmCertificateArn: certValid.certificateArn, sslSupportMethod: "sni-only", minimumProtocolVersion: "TLSv1.2_2021" },
  tags,
});

// Allow only this distribution to read the bucket.
new aws.s3.BucketPolicy("site-policy", {
  bucket: bucket.id,
  policy: pulumi.jsonStringify({
    Version: "2012-10-17",
    Statement: [{
      Effect: "Allow",
      Principal: { Service: "cloudfront.amazonaws.com" },
      Action: "s3:GetObject",
      Resource: pulumi.interpolate`${bucket.arn}/*`,
      Condition: { StringEquals: { "AWS:SourceArn": cdn.arn } },
    }],
  }),
});

new aws.route53.Record("site-alias", {
  zoneId,
  name: domain,
  type: "A",
  aliases: [{ name: cdn.domainName, zoneId: cdn.hostedZoneId, evaluateTargetHealth: false }],
});

export const url = pulumi.interpolate`https://${domain}`;
export const bucketName = bucket.bucket;
export const distributionId = cdn.id;

Resource names, managed policy IDs and argument shapes evolve between provider versions; treat this as a design to adapt, and check the current provider documentation before using it. Notice the design decisions: a provider alias for the certificate region, jsonStringify to embed outputs in a policy, an OAC instead of a public bucket, and provider, tags and parent all being the sort of things you would move into a component (see Component Resources).

Uploading files: content types and cache headers

Infrastructure is only half the job: files must be uploaded with the correct Content-Type and Cache-Control. A wrong content type makes the browser download a page instead of showing it. In Pulumi you can loop over a folder and create an aws.s3.BucketObjectv2 per file, or do the upload in CI with aws s3 sync. Either way, the rules are the same, so let us implement them once and test them.

Node.js Stand-in: content type and cache policy for each file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Rejecting unknown types prevents accidentally publishing files such as .env, .sql or source maps. Make the upload step an allow list.

Invalidating only what changed

CDN caches hold HTML for a while (or forever, if you set long TTLs). After a deploy you must tell the CDN which paths changed. Invalidating /* always works but costs money on busy sites and cold-starts the whole cache. Comparing hashes of the previous and new file lists gives a minimal set. Fingerprinted assets need no invalidation, because their names change.

Node.js Stand-in: compute a deploy plan from two manifests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note the subtlety: visitors holding old HTML may still request app.111111.js for a short time. A good deploy uploads new files before the HTML that references them, and removes old fingerprinted files only after a grace period.

Pipeline sketch

  1. PR: pulumi preview (infrastructure) and the site build with link checks.
  2. Merge: pulumi up for infrastructure, upload files with the allow list, run the invalidation plan.
  3. Scheduled: pulumi preview --refresh --expect-no-changes to catch drift in the CDN settings.
  4. Policy pack: reject public buckets and missing tags.

Extensions

  • Wrap the lot in a StaticSite component with args domain, zoneId and tags, then deploy several sites.
  • Add security headers with a CDN response-headers policy (HSTS, X-Content-Type-Options).
  • Add a unit test with mocks that asserts the bucket blocks public access and the distribution redirects to HTTPS.
  • Add a www to apex redirect.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the bucket kept private and read through an origin access control?

    A private bucket plus OAC means all reads go through the CDN, with your HTTPS, caching and headers.
  2. 2. Why use a separate provider for the certificate in the example?

    CloudFront only accepts ACM certificates from the us-east-1 region, so the certificate resources use a provider for that region.
  3. 3. Which Cache-Control fits an asset named app.3f9a1c.js?

    The hash in the name changes with the content, so the file can be cached for a year.
  4. 4. After a deploy, which paths need an invalidation?

    Fingerprinted files get new URLs. Files that keep their URL but change content need invalidation.

Summary

  • A private bucket behind a CDN with an origin access control is the safe default for static sites.
  • Certificates, DNS validation, aliases and policies are all resources; component wrapping makes them reusable.
  • Uploads need an allow list, correct content types and tiered cache headers.
  • Compare manifests to upload only changes and invalidate only same-URL files.
  • Add policy, tests and drift checks around the stack, as in the earlier lessons.

Next: Project: A Three-Tier Web App on Containers