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.
Before you begin#
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
- A current version of Go installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
- A current version of .NET installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
For this walkthrough, you'll need:
- A current version of the Pulumi CLI (Pulumi HCL requires no additional runtime)
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon S3 and CloudFront
Create a new project#
Create a new project from the template:
mkdir my-site; cd my-sitepulumi new static-website-aws-typescriptmkdir my-site; cd my-sitepulumi new static-website-aws-typescriptmkdir my-site; cd my-sitepulumi new static-website-aws-pythonmkdir my-site; cd my-sitepulumi new static-website-aws-pythonmkdir my-site; cd my-sitepulumi new static-website-aws-gomkdir my-site; cd my-sitepulumi new static-website-aws-gomkdir my-site; cd my-sitepulumi new static-website-aws-csharpmkdir my-site; cd my-sitepulumi new static-website-aws-csharpmkdir my-site; cd my-sitepulumi new static-website-aws-yamlmkdir my-site; cd my-sitepulumi new static-website-aws-yamlmkdir my-site; cd my-sitepulumi new static-website-aws-hclmkdir my-site; cd my-sitepulumi new static-website-aws-hclThe 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:
| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| indexDocument | The file to use for top-level pages | index.html |
| errorDocument | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set indexDocument <value>pulumi config set errorDocument <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set indexDocument "<value>"pulumi config set errorDocument "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| path | The path to the folder containing the website | www |
| index_document | The file to use for top-level pages | index.html |
| error_document | The file to use for error pages | error.html |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set path <value>pulumi config set index_document <value>pulumi config set error_document <value>pulumi config set aws:region "<value>"pulumi config set path "<value>"pulumi config set index_document "<value>"pulumi config set error_document "<value>"Review the code#
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the resources it declares.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains 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.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
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;import json
import pulumiimport pulumi_aws as awsimport pulumi_synced_folder as synced_folder
# Import the program's configuration settings.config = pulumi.Config()path = config.get("path") or "www"index_document = config.get("indexDocument") or "index.html"error_document = config.get("errorDocument") or "error.html"
# Create a private S3 bucket to hold the website content.bucket = aws.s3.Bucket("bucket")
# Block all public access to the bucket; CloudFront will reach it via OAC.public_access_block = aws.s3.BucketPublicAccessBlock( "public-access-block", bucket=bucket.bucket, block_public_acls=True, block_public_policy=True, ignore_public_acls=True, restrict_public_buckets=True,)
# Sync the website files to the bucket as private objects.bucket_folder = synced_folder.S3BucketFolder( "bucket-folder", acl="private", bucket_name=bucket.bucket, path=path, opts=pulumi.ResourceOptions(depends_on=[public_access_block]),)
# Create an Origin Access Control so CloudFront can read from the private bucket.origin_access_control = aws.cloudfront.OriginAccessControl( "origin-access-control", origin_access_control_origin_type="s3", signing_behavior="always", signing_protocol="sigv4",)
# Create a CloudFront CDN to distribute and cache the website.cdn = aws.cloudfront.Distribution( "cdn", enabled=True, default_root_object=index_document, origins=[ { "origin_id": bucket.arn, "domain_name": bucket.bucket_regional_domain_name, "origin_access_control_id": origin_access_control.id, } ], default_cache_behavior={ "target_origin_id": bucket.arn, "viewer_protocol_policy": "redirect-to-https", "allowed_methods": [ "GET", "HEAD", "OPTIONS", ], "cached_methods": [ "GET", "HEAD", "OPTIONS", ], "default_ttl": 600, "max_ttl": 600, "min_ttl": 600, "forwarded_values": { "query_string": True, "cookies": { "forward": "all", }, }, }, price_class="PriceClass_100", custom_error_responses=[ { "error_code": 404, "response_code": 404, "response_page_path": f"/{error_document}", } ], restrictions={ "geo_restriction": { "restriction_type": "none", }, }, viewer_certificate={ "cloudfront_default_certificate": True, },)
# Grant the CloudFront distribution permission to read objects from the bucket.bucket_policy = aws.s3.BucketPolicy( "bucket-policy", bucket=bucket.bucket, policy=pulumi.Output.all(bucket_arn=bucket.arn, cdn_arn=cdn.arn).apply( lambda args: json.dumps( { "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Principal": {"Service": "cloudfront.amazonaws.com"}, "Action": "s3:GetObject", "Resource": f"{args['bucket_arn']}/*", "Condition": { "StringEquals": {"AWS:SourceArn": args["cdn_arn"]}, }, }, } ) ),)
# Export the URL and hostname of the CloudFront distribution.pulumi.export("cdnURL", pulumi.Output.concat("https://", cdn.domain_name))pulumi.export("cdnHostname", cdn.domain_name)package main
import ( "encoding/json" "fmt"
"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/cloudfront" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/s3" synced "github.com/pulumi/pulumi-synced-folder/sdk/go/synced-folder" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config")
func main() { pulumi.Run(func(ctx *pulumi.Context) error {
// Import the program's configuration settings. cfg := config.New(ctx, "") path := "www" if param := cfg.Get("path"); param != "" { path = param } indexDocument := "index.html" if param := cfg.Get("indexDocument"); param != "" { indexDocument = param } errorDocument := "error.html" if param := cfg.Get("errorDocument"); param != "" { errorDocument = param }
// Create a private S3 bucket to hold the website content. bucket, err := s3.NewBucket(ctx, "bucket", nil) if err != nil { return err }
// Block all public access to the bucket; CloudFront will reach it via OAC. publicAccessBlock, err := s3.NewBucketPublicAccessBlock(ctx, "public-access-block", &s3.BucketPublicAccessBlockArgs{ Bucket: bucket.Bucket, BlockPublicAcls: pulumi.Bool(true), BlockPublicPolicy: pulumi.Bool(true), IgnorePublicAcls: pulumi.Bool(true), RestrictPublicBuckets: pulumi.Bool(true), }) if err != nil { return err }
// Sync the website files to the bucket as private objects. _, err = synced.NewS3BucketFolder(ctx, "bucket-folder", &synced.S3BucketFolderArgs{ Path: pulumi.String(path), BucketName: bucket.Bucket, Acl: pulumi.String("private"), }, pulumi.DependsOn([]pulumi.Resource{publicAccessBlock})) if err != nil { return err }
// Create an Origin Access Control so CloudFront can read from the private bucket. originAccessControl, err := cloudfront.NewOriginAccessControl(ctx, "origin-access-control", &cloudfront.OriginAccessControlArgs{ OriginAccessControlOriginType: pulumi.String("s3"), SigningBehavior: pulumi.String("always"), SigningProtocol: pulumi.String("sigv4"), }) if err != nil { return err }
// Create a CloudFront CDN to distribute and cache the website. cdn, err := cloudfront.NewDistribution(ctx, "cdn", &cloudfront.DistributionArgs{ Enabled: pulumi.Bool(true), DefaultRootObject: pulumi.String(indexDocument), Origins: cloudfront.DistributionOriginArray{ &cloudfront.DistributionOriginArgs{ OriginId: bucket.Arn, DomainName: bucket.BucketRegionalDomainName, OriginAccessControlId: originAccessControl.ID(), }, }, DefaultCacheBehavior: &cloudfront.DistributionDefaultCacheBehaviorArgs{ TargetOriginId: bucket.Arn, ViewerProtocolPolicy: pulumi.String("redirect-to-https"), AllowedMethods: pulumi.StringArray{ pulumi.String("GET"), pulumi.String("HEAD"), pulumi.String("OPTIONS"), }, CachedMethods: pulumi.StringArray{ pulumi.String("GET"), pulumi.String("HEAD"), pulumi.String("OPTIONS"), }, DefaultTtl: pulumi.Int(600), MaxTtl: pulumi.Int(600), MinTtl: pulumi.Int(600), ForwardedValues: &cloudfront.DistributionDefaultCacheBehaviorForwardedValuesArgs{ QueryString: pulumi.Bool(true), Cookies: &cloudfront.DistributionDefaultCacheBehaviorForwardedValuesCookiesArgs{ Forward: pulumi.String("all"), }, }, }, PriceClass: pulumi.String("PriceClass_100"), CustomErrorResponses: cloudfront.DistributionCustomErrorResponseArray{ &cloudfront.DistributionCustomErrorResponseArgs{ ErrorCode: pulumi.Int(404), ResponseCode: pulumi.Int(404), ResponsePagePath: pulumi.String(fmt.Sprintf("/%v", errorDocument)), }, }, Restrictions: &cloudfront.DistributionRestrictionsArgs{ GeoRestriction: &cloudfront.DistributionRestrictionsGeoRestrictionArgs{ RestrictionType: pulumi.String("none"), }, }, ViewerCertificate: &cloudfront.DistributionViewerCertificateArgs{ CloudfrontDefaultCertificate: pulumi.Bool(true), }, }) if err != nil { return err }
// Grant the CloudFront distribution permission to read objects from the bucket. _, err = s3.NewBucketPolicy(ctx, "bucket-policy", &s3.BucketPolicyArgs{ Bucket: bucket.Bucket, Policy: pulumi.All(bucket.Arn, cdn.Arn).ApplyT(func(args []interface{}) (string, error) { bucketArn := args[0].(string) cdnArn := args[1].(string) doc := map[string]interface{}{ "Version": "2012-10-17", "Statement": map[string]interface{}{ "Effect": "Allow", "Principal": map[string]interface{}{"Service": "cloudfront.amazonaws.com"}, "Action": "s3:GetObject", "Resource": fmt.Sprintf("%s/*", bucketArn), "Condition": map[string]interface{}{ "StringEquals": map[string]interface{}{"AWS:SourceArn": cdnArn}, }, }, } b, err := json.Marshal(doc) if err != nil { return "", err } return string(b), nil }).(pulumi.StringOutput), }) if err != nil { return err }
// Export the URL and hostname of the CloudFront distribution. ctx.Export("cdnURL", pulumi.Sprintf("https://%s", cdn.DomainName)) ctx.Export("cdnHostname", cdn.DomainName) return nil })}using System.Collections.Generic;using System.Text.Json;using Pulumi;using Aws = Pulumi.Aws;using SyncedFolder = Pulumi.SyncedFolder;
return await Deployment.RunAsync(() =>{ // Import the program's configuration settings. var config = new Config(); var path = config.Get("path") ?? "www"; var indexDocument = config.Get("indexDocument") ?? "index.html"; var errorDocument = config.Get("errorDocument") ?? "error.html";
// Create a private S3 bucket to hold the website content. var bucket = new Aws.S3.Bucket("bucket");
// Block all public access to the bucket; CloudFront will reach it via OAC. var publicAccessBlock = new Aws.S3.BucketPublicAccessBlock("public-access-block", new() { Bucket = bucket.Id, BlockPublicAcls = true, BlockPublicPolicy = true, IgnorePublicAcls = true, RestrictPublicBuckets = true, });
// Sync the website files to the bucket as private objects. var bucketFolder = new SyncedFolder.S3BucketFolder("bucket-folder", new() { Path = path, BucketName = bucket.BucketName, Acl = "private", }, new ComponentResourceOptions { DependsOn = { publicAccessBlock }, });
// Create an Origin Access Control so CloudFront can read from the private bucket. var originAccessControl = new Aws.CloudFront.OriginAccessControl("origin-access-control", new() { OriginAccessControlOriginType = "s3", SigningBehavior = "always", SigningProtocol = "sigv4", });
// Create a CloudFront CDN to distribute and cache the website. var cdn = new Aws.CloudFront.Distribution("cdn", new() { Enabled = true, DefaultRootObject = indexDocument, Origins = new[] { new Aws.CloudFront.Inputs.DistributionOriginArgs { OriginId = bucket.Arn, DomainName = bucket.BucketRegionalDomainName, OriginAccessControlId = originAccessControl.Id, }, }, DefaultCacheBehavior = new Aws.CloudFront.Inputs.DistributionDefaultCacheBehaviorArgs { TargetOriginId = bucket.Arn, ViewerProtocolPolicy = "redirect-to-https", AllowedMethods = new[] { "GET", "HEAD", "OPTIONS", }, CachedMethods = new[] { "GET", "HEAD", "OPTIONS", }, DefaultTtl = 600, MaxTtl = 600, MinTtl = 600, ForwardedValues = new Aws.CloudFront.Inputs.DistributionDefaultCacheBehaviorForwardedValuesArgs { QueryString = true, Cookies = new Aws.CloudFront.Inputs.DistributionDefaultCacheBehaviorForwardedValuesCookiesArgs { Forward = "all", }, }, }, PriceClass = "PriceClass_100", CustomErrorResponses = new[] { new Aws.CloudFront.Inputs.DistributionCustomErrorResponseArgs { ErrorCode = 404, ResponseCode = 404, ResponsePagePath = $"/{errorDocument}", }, }, Restrictions = new Aws.CloudFront.Inputs.DistributionRestrictionsArgs { GeoRestriction = new Aws.CloudFront.Inputs.DistributionRestrictionsGeoRestrictionArgs { RestrictionType = "none", }, }, ViewerCertificate = new Aws.CloudFront.Inputs.DistributionViewerCertificateArgs { CloudfrontDefaultCertificate = true, }, });
// Grant the CloudFront distribution permission to read objects from the bucket. var bucketPolicy = new Aws.S3.BucketPolicy("bucket-policy", new() { Bucket = bucket.Id, Policy = Output.Tuple(bucket.Arn, cdn.Arn).Apply(arns => { var (bucketArn, cdnArn) = arns; return JsonSerializer.Serialize(new { Version = "2012-10-17", Statement = new { Effect = "Allow", Principal = new { Service = "cloudfront.amazonaws.com" }, Action = "s3:GetObject", Resource = $"{bucketArn}/*", Condition = new { StringEquals = new Dictionary<string, string> { { "AWS:SourceArn", cdnArn }, }, }, }, }); }), });
// Export the URL and hostname of the CloudFront distribution. return new Dictionary<string, object?> { ["cdnURL"] = Output.Format($"https://{cdn.DomainName}"), ["cdnHostname"] = cdn.DomainName, };});name: my-projectdescription: A Pulumi YAML program to deploy a static website on AWSruntime: yaml
# Import the program's configuration settings.config: path: type: string default: www indexDocument: type: string default: index.html errorDocument: type: string default: error.html
resources:
# Create a private S3 bucket to hold the website content. bucket: type: aws:s3:Bucket
# Block all public access to the bucket; CloudFront will reach it via OAC. public-access-block: type: aws:s3:BucketPublicAccessBlock properties: bucket: ${bucket.id} blockPublicAcls: true blockPublicPolicy: true ignorePublicAcls: true restrictPublicBuckets: true
# Sync the website files to the bucket as private objects. bucket-folder: type: synced-folder:index:S3BucketFolder options: dependsOn: - ${public-access-block} properties: acl: private bucketName: ${bucket.bucket} path: ${path}
# Create an Origin Access Control so CloudFront can read from the private bucket. origin-access-control: type: aws:cloudfront:OriginAccessControl properties: originAccessControlOriginType: s3 signingBehavior: always signingProtocol: sigv4
# Create a CloudFront CDN to distribute and cache the website. cdn: type: aws:cloudfront:Distribution properties: enabled: true defaultRootObject: ${indexDocument} origins: - originId: ${bucket.arn} domainName: ${bucket.bucketRegionalDomainName} originAccessControlId: ${origin-access-control.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. bucket-policy: type: aws:s3:BucketPolicy properties: bucket: ${bucket.id} policy: fn::toJSON: Version: "2012-10-17" Statement: Effect: Allow Principal: Service: cloudfront.amazonaws.com Action: s3:GetObject Resource: ${bucket.arn}/* Condition: StringEquals: "AWS:SourceArn": ${cdn.arn}
# Export the URL and hostname of the CloudFront distribution.outputs: cdnURL: https://${cdn.domainName} cdnHostname: ${cdn.domainName}terraform { required_providers { aws = { source = "pulumi/aws" } synced-folder = { source = "pulumi/synced-folder" } }}
variable "path" { description = "The path to the folder containing the website" type = string default = "www"}
variable "index_document" { description = "The file to use for top-level pages" type = string default = "index.html"}
variable "error_document" { description = "The file to use for error pages" type = string default = "error.html"}
# Create a private S3 bucket to hold the website content.resource "aws_s3_bucket" "bucket" {}
# Block all public access to the bucket; CloudFront will reach it via OAC.resource "aws_s3_bucket_public_access_block" "public-access-block" { bucket = aws_s3_bucket.bucket.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true}
# Sync the website files to the bucket as private objects.resource "synced-folder_s3_bucket_folder" "bucket-folder" { depends_on = [aws_s3_bucket_public_access_block.public-access-block] acl = "private" bucket_name = aws_s3_bucket.bucket.bucket path = var.path}
# Create an Origin Access Control so CloudFront can read from the private bucket.resource "aws_cloudfront_origin_access_control" "origin-access-control" { origin_access_control_origin_type = "s3" signing_behavior = "always" signing_protocol = "sigv4"}
# Create a CloudFront CDN to distribute and cache the website.resource "aws_cloudfront_distribution" "cdn" { enabled = true default_root_object = var.index_document price_class = "PriceClass_100"
origin { origin_id = aws_s3_bucket.bucket.arn domain_name = aws_s3_bucket.bucket.bucket_regional_domain_name origin_access_control_id = aws_cloudfront_origin_access_control.origin-access-control.id }
default_cache_behavior { target_origin_id = aws_s3_bucket.bucket.arn viewer_protocol_policy = "redirect-to-https" allowed_methods = ["GET", "HEAD", "OPTIONS"] cached_methods = ["GET", "HEAD", "OPTIONS"] default_ttl = 600 max_ttl = 600 min_ttl = 600
forwarded_values { query_string = true cookies { forward = "all" } } }
custom_error_response { error_code = 404 response_code = 404 response_page_path = "/${var.error_document}" }
restrictions { geo_restriction { restriction_type = "none" } }
viewer_certificate { cloudfront_default_certificate = true }}
# Grant the CloudFront distribution permission to read objects from the bucket.resource "aws_s3_bucket_policy" "bucket-policy" { bucket = aws_s3_bucket.bucket.id policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Principal = { Service = "cloudfront.amazonaws.com" } Action = "s3:GetObject" Resource = "${aws_s3_bucket.bucket.arn}/*" Condition = { StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.cdn.arn } } }] })}
# Export the URL and hostname of the CloudFront distribution.output "cdn_url" { value = "https://${aws_cloudfront_distribution.cdn.domain_name}"}
output "cdn_hostname" { value = aws_cloudfront_distribution.cdn.domain_name}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.
pulumi uppulumi upPulumi 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
CNAMErecords to associate custom domains.- cdnURL
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdnHostname
The provider-assigned hostname of the CloudFront CDN. Useful for creating
CNAMErecords to associate custom domains.- cdnURL
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdnHostname
The provider-assigned hostname of the CloudFront CDN. Useful for creating
CNAMErecords to associate custom domains.- cdnURL
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdnHostname
The provider-assigned hostname of the CloudFront CDN. Useful for creating
CNAMErecords to associate custom domains.- cdnURL
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdnHostname
The provider-assigned hostname of the CloudFront CDN. Useful for creating
CNAMErecords to associate custom domains.- cdnURL
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdn_url
The fully-qualified HTTPS URL of the CloudFront CDN.
- cdn_hostname
The provider-assigned hostname of the CloudFront CDN. Useful for creating
CNAMErecords to associate custom domains.
Read one any time with pulumi stack output <name>, or pass it to another command. This opens the site in your browser:
open $(pulumi stack output cdnURL)xdg-open $(pulumi stack output cdnURL)Start-Process $(pulumi stack output cdnURL)open $(pulumi stack output cdnURL)xdg-open $(pulumi stack output cdnURL)Start-Process $(pulumi stack output cdnURL)open $(pulumi stack output cdnURL)xdg-open $(pulumi stack output cdnURL)Start-Process $(pulumi stack output cdnURL)open $(pulumi stack output cdnURL)xdg-open $(pulumi stack output cdnURL)Start-Process $(pulumi stack output cdnURL)open $(pulumi stack output cdnURL)xdg-open $(pulumi stack output cdnURL)Start-Process $(pulumi stack output cdnURL)open $(pulumi stack output cdn_url)xdg-open $(pulumi stack output cdn_url)Start-Process $(pulumi stack output cdn_url)To check it from the terminal, fetch the page with curl. It prints the template’s placeholder page, which says Hello, world!:
curl -s $(pulumi stack output cdnURL)curl.exe -s $(pulumi stack output cdnURL)curl -s $(pulumi stack output cdnURL)curl.exe -s $(pulumi stack output cdnURL)curl -s $(pulumi stack output cdnURL)curl.exe -s $(pulumi stack output cdnURL)curl -s $(pulumi stack output cdnURL)curl.exe -s $(pulumi stack output cdnURL)curl -s $(pulumi stack output cdnURL)curl.exe -s $(pulumi stack output cdnURL)curl -s $(pulumi stack output cdn_url)curl.exe -s $(pulumi stack output cdn_url)Need help?
If pulumi up reports No valid credential sources found or ExpiredToken, sign in again:
aws loginaws loginStill 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.
- 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.
- 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.
- 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.
- 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.
- 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.- index_document
The file to use for top-level pages. Defaults to
index.html.- error_document
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:
pulumi config set path ../my-existing-website/buildpulumi uppulumi config set path ../my-existing-website/buildpulumi upAdjusting 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.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
const cdn = new aws.cloudfront.Distribution("cdn", { defaultCacheBehavior: { defaultTtl: 600, maxTtl: 600, minTtl: 600, defaultTtl: 3600, maxTtl: 3600, minTtl: 3600,cdn = aws.cloudfront.Distribution( "cdn", default_cache_behavior={ "default_ttl": 600, "max_ttl": 600, "min_ttl": 600, "default_ttl": 3600, "max_ttl": 3600, "min_ttl": 3600,cdn, err := cloudfront.NewDistribution(ctx, "cdn", &cloudfront.DistributionArgs{ DefaultCacheBehavior: &cloudfront.DistributionDefaultCacheBehaviorArgs{ DefaultTtl: pulumi.Int(600), MaxTtl: pulumi.Int(600), MinTtl: pulumi.Int(600), DefaultTtl: pulumi.Int(3600), MaxTtl: pulumi.Int(3600), MinTtl: pulumi.Int(3600),var cdn = new Aws.CloudFront.Distribution("cdn", new(){ DefaultCacheBehavior = new Aws.CloudFront.Inputs.DistributionDefaultCacheBehaviorArgs { DefaultTtl = 600, MaxTtl = 600, MinTtl = 600, DefaultTtl = 3600, MaxTtl = 3600, MinTtl = 3600,cdn: type: aws:cloudfront:Distribution properties: defaultCacheBehavior: defaultTtl: 600 maxTtl: 600 minTtl: 600 defaultTtl: 3600 maxTtl: 3600 minTtl: 3600resource "aws_cloudfront_distribution" "cdn" { default_cache_behavior { default_ttl = 600 max_ttl = 600 min_ttl = 600 default_ttl = 3600 max_ttl = 3600 min_ttl = 3600Deploy the change with pulumi up. The preview shows one resource to update, the cdn distribution:
pulumi uppulumi upAlternatively, 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:
pulumi config set domain example.compulumi config set subdomain wwwpulumi config set domain example.compulumi config set subdomain wwwThen, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf 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:
Then, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf 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:
Then, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf 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:
Then, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf 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:
Then, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf 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:
Then, in your editor of choice, open index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf and add the following lines to the top of the program to declare the new variables and capture the domain as a reusable value:
const domain = config.require("domain");const subdomain = config.require("subdomain");const domainName = `${subdomain}.${domain}`;domain = config.require("domain");subdomain = config.require("subdomain");domain_name = f"{subdomain}.{domain}";domain := cfg.Require("domain")subdomain := cfg.Require("subdomain")domainName := fmt.Sprintf("%s.%s", subdomain, domain)var domain = config.Require("domain");var subdomain = config.Require("subdomain");var domainName = $"{subdomain}.{domain}";config: # ... domain: type: string subdomain: type: string
variables: domainName: ${subdomain}.${domain}variable "domain" { type = string}
variable "subdomain" { type = string}
locals { domain_name = "${var.subdomain}.${var.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):
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):
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):
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):
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):
Next, just above the aws_cloudfront_distribution resource, 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,});# Look up your existing Route 53 hosted zone.zone = aws.route53.get_zone_output(name=domain)
# Provision a new ACM certificate.certificate = aws.acm.Certificate( "certificate", domain_name=domain_name, validation_method="DNS", opts=pulumi.ResourceOptions( # ACM certificates must be created in the us-east-1 region. provider=aws.Provider("us-east-provider", region="us-east-1"), ),);
# Validate the ACM certificate with DNS.options = certificate.domain_validation_options.apply(lambda options: options[0])certificate_validation = aws.route53.Record( "certificate-validation", name=options.resource_record_name, type=options.resource_record_type, records=[options.resource_record_value], zone_id=zone.zone_id, ttl=60,);// Look up your existing Route 53 hosted zone.zone, err := route53.LookupZone(ctx, &route53.LookupZoneArgs{ Name: pulumi.StringRef(domain),}, nil)if err != nil { return err}
// Provision a new ACM certificate in the us-east-1 region.provider, _ := aws.NewProvider(ctx, "us-east-provider", &aws.ProviderArgs{ Region: pulumi.StringPtr("us-east-1"),})certificate, err := acm.NewCertificate(ctx, "certificate", &acm.CertificateArgs{ DomainName: pulumi.String(domainName), ValidationMethod: pulumi.String("DNS"),}, pulumi.Provider(provider))if err != nil { return err}
validationOption := certificate.DomainValidationOptions.Index(pulumi.Int(0))_, err = route53.NewRecord(ctx, "certificate-validation", &route53.RecordArgs{ Name: validationOption.ResourceRecordName().Elem(), Type: validationOption.ResourceRecordType().Elem(), Records: pulumi.StringArray{ validationOption.ResourceRecordValue().Elem(), }, ZoneId: pulumi.String(zone.ZoneId), Ttl: pulumi.Int(60),})if err != nil { return err}You’ll need these imports as well, for the AWS provider, ACM and Route 53:
import ( // ... "github.com/pulumi/pulumi-aws/sdk/v7/go/aws" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/acm" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/route53")// Look up your existing Route 53-managed zone.var zone = Aws.Route53.GetZone.Invoke(new(){ Name = domain,});
// Provision a new ACM certificate.var certificate = new Aws.Acm.Certificate("certificate", new(){ DomainName = domainName, ValidationMethod = "DNS",},// ACM certificates must be created in the us-east-1 region.new CustomResourceOptions { Provider = new Aws.Provider("us-east-provider", new() { Region = "us-east-1", })});
// Validate the ACM certificate with DNS.var validationOption = certificate.DomainValidationOptions.GetAt(0);var certificateValidation = new Aws.Route53.Record("certificate-validation", new(){ Name = validationOption.Apply(option => option.ResourceRecordName!), Type = validationOption.Apply(option => option.ResourceRecordType!), Records = new[] { validationOption.Apply(option => option.ResourceRecordValue!), }, ZoneId = zone.Apply(zone => zone.ZoneId), Ttl = 60,});variables: # ...
# Add this block to the variables section to look up your existing # Route 53 hosted zone. zone: Fn::Invoke: Function: aws:route53:getZone Arguments: name: ${domain}
resources: # ...
# ACM certificates must be provisioned in the us-east-1 region, so # we configure an explicit provider for this resource. us-east-provider: type: pulumi:providers:aws properties: region: us-east-1
# Provision a new ACM certificate. certificate: type: aws:acm:Certificate properties: domainName: ${domainName} validationMethod: DNS options: # ACM certificates must be created in the us-east-1 region. provider: ${us-east-provider}
# Validate the ACM certificate with DNS. certificateValidation: type: aws:route53:Record properties: name: ${certificate.domainValidationOptions[0].resourceRecordName} type: ${certificate.domainValidationOptions[0].resourceRecordType} zoneId: ${zone.zoneId} ttl: 60 records: - ${certificate.domainValidationOptions[0].resourceRecordValue}# Look up your existing Route 53 hosted zone.data "aws_route53_zone" "zone" { name = var.domain}
# ACM certificates for CloudFront must be created in the us-east-1 region.provider "aws" { alias = "us_east_1" region = "us-east-1"}
# Provision a new ACM certificate.resource "aws_acm_certificate" "certificate" { provider = aws.us_east_1 domain_name = local.domain_name validation_method = "DNS"}
# Validate the ACM certificate with DNS.resource "aws_route53_record" "certificate_validation" { for_each = { for option in aws_acm_certificate.certificate.domain_validation_options : option.domain_name => { name = option.resource_record_name type = option.resource_record_type record = option.resource_record_value } }
zone_id = data.aws_route53_zone.zone.zone_id name = each.value.name type = each.value.type records = [each.value.record] 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:
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:
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:
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:
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:
Extend the CloudFront configuration to handle requests for the new domain by adding an aliases argument to the CDN configuration and adjusting the viewer_certificate block 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", },});cdn = aws.cloudfront.Distribution( # ... aliases=[ domain_name, ], viewer_certificate=aws.cloudfront.DistributionViewerCertificateArgs( cloudfront_default_certificate=False, acm_certificate_arn=certificate.arn, ssl_support_method="sni-only", ),)cdn, err := cloudfront.NewDistribution(ctx, "cdn", &cloudfront.DistributionArgs{ // ... Aliases: &pulumi.StringArray{ pulumi.String(domainName), }, ViewerCertificate: &cloudfront.DistributionViewerCertificateArgs{ CloudfrontDefaultCertificate: pulumi.Bool(false), AcmCertificateArn: certificate.Arn, SslSupportMethod: pulumi.String("sni-only"), },})var cdn = new Aws.CloudFront.Distribution("cdn", new(){ // ... Aliases = new[] { domainName }, ViewerCertificate = new Aws.CloudFront.Inputs.DistributionViewerCertificateArgs { CloudfrontDefaultCertificate = false, AcmCertificateArn = certificate.Arn, SslSupportMethod = "sni-only", },});cdn: type: aws:cloudfront:Distribution properties: # ... aliases: - ${domainName} viewerCertificate: cloudfrontDefaultCertificate: false acmCertificateArn: ${certificate.arn} sslSupportMethod: sni-onlyresource "aws_cloudfront_distribution" "cdn" { # ... aliases = [local.domain_name]
viewer_certificate { cloudfront_default_certificate = false acm_certificate_arn = aws_acm_certificate.certificate.arn ssl_support_method = "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 });# Create a DNS A record to point to the CDN.my_site = aws.route53.Record(domain_name, zone_id=zone.zone_id, name=subdomain, type="A", aliases=[ aws.route53.RecordAliasArgs( name=cdn.domain_name, zone_id=cdn.hosted_zone_id, evaluate_target_health=True, ) ], opts=pulumi.ResourceOptions( depends_on=certificate, ),)// Create a DNS A record to point to the CDN._, err = route53.NewRecord(ctx, domainName, &route53.RecordArgs{ Name: pulumi.String(subdomain), ZoneId: pulumi.String(zone.ZoneId), Type: pulumi.String("A"), Aliases: route53.RecordAliasArray{ &route53.RecordAliasArgs{ Name: cdn.DomainName, ZoneId: cdn.HostedZoneId, EvaluateTargetHealth: pulumi.Bool(true), }, },}, pulumi.DependsOn([]pulumi.Resource{certificate}))if err != nil { return err}// Create a DNS A record to point to the CDN.var record = new Aws.Route53.Record(domainName, new(){ Name = subdomain, ZoneId = zone.Apply(zone => zone.ZoneId), Type = "A", Aliases = new[] { new Aws.Route53.Inputs.RecordAliasArgs { Name = cdn.DomainName, ZoneId = cdn.HostedZoneId, EvaluateTargetHealth = true, } },},new CustomResourceOptions { DependsOn = certificate,});resources: # ...
# Create a DNS A record to point to the CDN. ${domainName}: type: aws:route53:Record properties: name: ${subdomain} zoneId: ${zone.zoneId} type: A aliases: - name: ${cdn.domainName} zoneId: ${cdn.hostedZoneId} evaluateTargetHealth: true options: dependsOn: - ${certificate}# Create a DNS A record to point to the CDN.resource "aws_route53_record" "domain" { zone_id = data.aws_route53_zone.zone.zone_id name = var.subdomain type = "A"
alias { name = aws_cloudfront_distribution.cdn.domain_name zone_id = aws_cloudfront_distribution.cdn.hosted_zone_id evaluate_target_health = true }
depends_on = [aws_acm_certificate.certificate]}And finally, complete the program by exporting the new URL as a Pulumi stack output:
export const domainURL = `https://${domainName}`;pulumi.export("domainURL", f"https://{domain_name}")ctx.Export("domainURL", pulumi.Sprintf("https://%s", domainName))["domainURL"] = $"https://{subdomain}.{domain}",outputs: # ... domainURL: https://${domainName}output "domain_url" { value = "https://${local.domain_name}"}Save your changes, then preview and deploy with another pulumi up:
pulumi uppulumi upIn a few moments, you should be able to browse to your website using the custom domain:
open $(pulumi stack output domainURL)xdg-open $(pulumi stack output domainURL)Start-Process $(pulumi stack output domainURL)open $(pulumi stack output domainURL)xdg-open $(pulumi stack output domainURL)Start-Process $(pulumi stack output domainURL)open $(pulumi stack output domainURL)xdg-open $(pulumi stack output domainURL)Start-Process $(pulumi stack output domainURL)open $(pulumi stack output domainURL)xdg-open $(pulumi stack output domainURL)Start-Process $(pulumi stack output domainURL)open $(pulumi stack output domainURL)xdg-open $(pulumi stack output domainURL)Start-Process $(pulumi stack output domainURL)open $(pulumi stack output domain_url)xdg-open $(pulumi stack output domain_url)Start-Process $(pulumi stack output domain_url)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:
pulumi stack output cdnHostnamepulumi stack output cdnHostnameIf 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:
pulumi stack output cdnHostnamepulumi stack output cdnHostnameIf 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:
pulumi stack output cdnHostnamepulumi stack output cdnHostnameIf 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:
pulumi stack output cdnHostnamepulumi stack output cdnHostnameIf 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:
pulumi stack output cdnHostnamepulumi stack output cdnHostnameIf the domain you’d like to use is being managed by a third-party DNS service, you can generally use the exported cdn_hostname to create a CNAME record with your DNS provider. You can obtain this value with pulumi stack output:
pulumi stack output cdn_hostnamepulumi stack output cdn_hostnamePulumi 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:
pulumi destroypulumi destroyLearn more#
- Browse other architecture templates in the Templates gallery.
- Explore the AWS provider API docs in the Pulumi Registry.
- Walk through Pulumi from the ground up in Pulumi Tutorials.
- Read the latest AWS posts on the Pulumi blog.