Skip to main content

Search the Dev Center

Search tutorials, templates, examples, and more.

AWS Static Website

The AWS Static Website template scaffolds a Pulumi project that stores site files in a private Amazon S3 bucket and serves them through an Amazon CloudFront distribution using Origin Access Control. The bucket isn’t publicly readable; CloudFront authenticates to the S3 REST endpoint via a bucket policy scoped to the distribution. The template ships with placeholder web content so the project deploys end to end out of the box.

Architecture diagram of the AWS Static Website template AWS CloudFrontDistribution S3 Bucket

Before you begin#

For this walkthrough, you'll need:

Create a new project#

Create a new project from the template:

Terminal window
mkdir my-site; cd my-site
pulumi new static-website-aws-typescript

The pulumi new command walks you through creating and configuring the new project and stack. A stack is an instance of a project, and you can have many of them (dev, staging, prod), each with its own configuration settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.

This template’s settings include:

KeyDescriptionDefault
aws:regionThe AWS region to deploy intous-west-2
pathThe path to the folder containing the websitewww
indexDocumentThe file to use for top-level pagesindex.html
errorDocumentThe file to use for error pageserror.html
You can change values like these later with pulumi config set :
Terminal window
pulumi config set aws:region <value>
pulumi config set path <value>
pulumi config set indexDocument <value>
pulumi config set errorDocument <value>

Review the code#

When setup completes, you’ll see a few files:

  • Pulumi.yaml contains the project name and the language it’s written in.
  • Pulumi.dev.yaml contains the dev stack’s settings, including the values you just entered.
  • index.ts contains the program code that declares your cloud resources.

Take a moment to open them up and have a look. Here’s what’s in index.ts:

index.ts
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as synced_folder from "@pulumi/synced-folder";
// Import the program's configuration settings.
const config = new pulumi.Config();
const path = config.get("path") || "www";
const indexDocument = config.get("indexDocument") || "index.html";
const errorDocument = config.get("errorDocument") || "error.html";
// Create a private S3 bucket to hold the website content.
const bucket = new aws.s3.Bucket("bucket");
// Block all public access to the bucket; CloudFront will reach it via OAC.
const publicAccessBlock = new aws.s3.BucketPublicAccessBlock("public-access-block", {
bucket: bucket.bucket,
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
});
// Sync the website files to the bucket as private objects.
const bucketFolder = new synced_folder.S3BucketFolder("bucket-folder", {
path: path,
bucketName: bucket.bucket,
acl: "private",
}, { dependsOn: [publicAccessBlock] });
// Create an Origin Access Control so CloudFront can read from the private bucket.
const originAccessControl = new aws.cloudfront.OriginAccessControl("origin-access-control", {
originAccessControlOriginType: "s3",
signingBehavior: "always",
signingProtocol: "sigv4",
});
// Create a CloudFront CDN to distribute and cache the website.
const cdn = new aws.cloudfront.Distribution("cdn", {
enabled: true,
defaultRootObject: indexDocument,
origins: [{
originId: bucket.arn,
domainName: bucket.bucketRegionalDomainName,
originAccessControlId: originAccessControl.id,
}],
defaultCacheBehavior: {
targetOriginId: bucket.arn,
viewerProtocolPolicy: "redirect-to-https",
allowedMethods: [
"GET",
"HEAD",
"OPTIONS",
],
cachedMethods: [
"GET",
"HEAD",
"OPTIONS",
],
defaultTtl: 600,
maxTtl: 600,
minTtl: 600,
forwardedValues: {
queryString: true,
cookies: {
forward: "all",
},
},
},
priceClass: "PriceClass_100",
customErrorResponses: [{
errorCode: 404,
responseCode: 404,
responsePagePath: `/${errorDocument}`,
}],
restrictions: {
geoRestriction: {
restrictionType: "none",
},
},
viewerCertificate: {
cloudfrontDefaultCertificate: true,
},
});
// Grant the CloudFront distribution permission to read objects from the bucket.
const bucketPolicy = new aws.s3.BucketPolicy("bucket-policy", {
bucket: bucket.bucket,
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 },
},
},
}),
});
// Export the URL and hostname of the CloudFront distribution.
export const cdnURL = pulumi.interpolate`https://${cdn.domainName}`;
export const cdnHostname = cdn.domainName;

Deploy the project#

Deploy with pulumi up. It starts with a preview of what it’s about to create and asks before it changes anything. Choose yes to deploy.

Terminal window
pulumi up

Pulumi adds a random suffix to most resource names, so the S3 bucket bucket becomes something like bucket-4f8a2c1. This is autonaming. It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.

When it finishes, Pulumi prints the stack’s outputs, values it only knows once the resources exist:

cdnHostname

The provider-assigned hostname of the CloudFront CDN. Useful for creating CNAME records to associate custom domains.

cdnURL

The fully-qualified HTTPS URL of the CloudFront CDN.

Read one any time with pulumi stack output <name>, or pass it to another command. This opens the site in your browser:

Terminal window
open $(pulumi stack output cdnURL)

To check it from the terminal, fetch the page with curl. It prints the template’s placeholder page, which says Hello, world!:

Terminal window
curl -s $(pulumi stack output cdnURL)
Need help?

If pulumi up reports No valid credential sources found or ExpiredToken, sign in again:

Terminal window
aws login

Still stuck? Let us know.

Customize the project#

Projects created with this template expose the following configuration settings:

path

The path to the folder containing the files of the website. Defaults to www, which is the name (and relative path) of the folder included with the template.

indexDocument

The file to use for top-level pages. Defaults to index.html.

errorDocument

The file to use for error pages. Defaults to error.html.

All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, Pulumi.dev.yaml) or by changing their values with pulumi config set.

Using your own web content#

If you already have a static website you’d like to deploy on AWS with Pulumi, you can do so either by replacing placeholder content in the www folder or by configuring the stack to point to another folder on your computer with the path setting. Replace ../my-existing-website/build with the path to your site’s files:

Terminal window
pulumi config set path ../my-existing-website/build
pulumi up

Adjusting your cache settings#

By default, the generated program configures the CloudFront CDN to cache files for 600 seconds (10 minutes), which may or may not be the best fit for your project or stack. You can adjust these settings by changing the code in index.ts:

const cdn = new aws.cloudfront.Distribution("cdn", {
defaultCacheBehavior: {
defaultTtl: 600,
maxTtl: 600,
minTtl: 600,
defaultTtl: 3600,
maxTtl: 3600,
minTtl: 3600,

Deploy the change with pulumi up. The preview shows one resource to update, the cdn distribution:

Terminal window
pulumi up

Alternatively, and perhaps better, you could make these settings configurable as well, which would allow them to vary between other stacks in your project.

To see what else you can add, browse the AWS provider in the Pulumi Registry.

Next steps#

Templated projects are meant to be customized, and every web project comes with its own unique set of needs. This section includes a few examples aimed at helping you to adapt your new project to address some of the more common ones.

Adding a custom domain#

Once your website is deployed on AWS, you may want to give it a domain of its own. For this, you have many options, and they generally fall into one of two categories: using Amazon Route 53, which is a good choice if your domain is already being managed on AWS, or using a third-party service like DNSimple or Google Cloud DNS. Both options are easily managed with Pulumi.

Using a Route 53 managed domain#

If the domain you’d like to use is already configured as a Route 53 hosted zone, you can easily add a subdomain for your website by making a few small changes to your program.

To do so, start by adding two new configuration settings — one for the domain, another for subdomain to use for the website:

Terminal window
pulumi config set domain example.com
pulumi config set subdomain www

Then, in your editor of choice, open index.ts and add the following lines to the configuration section at the top of the program to import the new settings and capture the domain as a reusable value:

const domain = config.require("domain");
const subdomain = config.require("subdomain");
const domainName = `${subdomain}.${domain}`;

Next, just above the aws.cloudfront.Distribution declaration, add these lines to provision and validate a new SSL/TLS certificate with AWS Certificate Manager (ACM):

// Look up your existing Route 53 hosted zone.
const zone = aws.route53.getZoneOutput({ name: domain });
// Provision a new ACM certificate.
const certificate = new aws.acm.Certificate("certificate",
{
domainName: domainName,
validationMethod: "DNS",
},
{
// ACM certificates must be created in the us-east-1 region.
provider: new aws.Provider("us-east-provider", {
region: "us-east-1",
}),
},
);
// Validate the ACM certificate with DNS.
const validationOption = certificate.domainValidationOptions[0];
const certificateValidation = new aws.route53.Record("certificate-validation", {
name: validationOption.resourceRecordName,
type: validationOption.resourceRecordType,
records: [ validationOption.resourceRecordValue ],
zoneId: zone.zoneId,
ttl: 60,
});

Extend the CloudFront configuration to handle requests for the new domain by adding an aliases argument to the CDN configuration and adjusting viewerCertificate to use the newly provisioned ACM certificate:

const cdn = new aws.cloudfront.Distribution("cdn", {
// ...
aliases: [
domainName,
],
viewerCertificate: {
cloudfrontDefaultCertificate: false,
acmCertificateArn: certificate.arn,
sslSupportMethod: "sni-only",
},
});

Below that, add a Route 53 A record to create a DNS record pointing to the CloudFront CDN:

// Create a DNS A record to point to the CDN.
const record = new aws.route53.Record(domainName, {
name: subdomain,
zoneId: zone.zoneId,
type: "A",
aliases: [
{
name: cdn.domainName,
zoneId: cdn.hostedZoneId,
evaluateTargetHealth: true,
}
],
}, { dependsOn: certificate });

And finally, complete the program by exporting the new URL as a Pulumi stack output:

export const domainURL = `https://${domainName}`;

Save your changes, then preview and deploy with another pulumi up:

Terminal window
pulumi up

In a few moments, you should be able to browse to your website using the custom domain:

Terminal window
open $(pulumi stack output domainURL)

Using a third-party DNS service#

If the domain you’d like to use is being managed by a third-party DNS service, you can generally use the exported cdnHostname to create a CNAME record with your DNS provider. You can obtain this value with pulumi stack output:

Terminal window
pulumi stack output cdnHostname

Pulumi supports many third-party DNS providers, all of which are available in the Pulumi Registry and accompanied by examples, including:

Integration details vary by provider, so we suggest exploring the Pulumi API documentation of your provider of choice to learn more. See the Registry for a complete list of supported providers.

Cleaning up#

You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:

Terminal window
pulumi destroy

Learn more#

Related

The infrastructure platform for humans and agents.