Skip to content

Resource: awsCloudfrontDistribution

Creates an Amazon CloudFront web distribution.

For information about CloudFront distributions, see the Amazon CloudFront Developer Guide. For specific information about creating CloudFront web distributions, see the POST Distribution page in the Amazon CloudFront API Reference.

\~> NOTE: CloudFront distributions take about 15 minutes to reach a deployed state after creation or modification. During this time, deletes to resources will be blocked. If you need to delete a distribution that is enabled and you do not want to wait, you need to use the retainOnDelete flag.

Example Usage

The following example below creates a CloudFront distribution with an S3 origin.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const s3OriginId = "myS3Origin";
const awsS3BucketB = new aws.s3Bucket.S3Bucket(this, "b", {
  bucket: "mybucket",
  tags: {
    Name: "My bucket",
  },
});
new aws.s3BucketAcl.S3BucketAcl(this, "b_acl", {
  acl: "private",
  bucket: awsS3BucketB.id,
});
new aws.cloudfrontDistribution.CloudfrontDistribution(this, "s3_distribution", {
  aliases: ["mysite.example.com", "yoursite.example.com"],
  comment: "Some comment",
  defaultCacheBehavior: {
    allowedMethods: [
      "DELETE",
      "GET",
      "HEAD",
      "OPTIONS",
      "PATCH",
      "POST",
      "PUT",
    ],
    cachedMethods: ["GET", "HEAD"],
    defaultTtl: 3600,
    forwardedValues: {
      cookies: {
        forward: "none",
      },
      queryString: false,
    },
    maxTtl: 86400,
    minTtl: 0,
    targetOriginId: s3OriginId,
    viewerProtocolPolicy: "allow-all",
  },
  defaultRootObject: "index.html",
  enabled: true,
  isIpv6Enabled: true,
  loggingConfig: {
    bucket: "mylogs.s3.amazonaws.com",
    includeCookies: false,
    prefix: "myprefix",
  },
  orderedCacheBehavior: [
    {
      allowedMethods: ["GET", "HEAD", "OPTIONS"],
      cachedMethods: ["GET", "HEAD", "OPTIONS"],
      compress: true,
      defaultTtl: 86400,
      forwardedValues: {
        cookies: {
          forward: "none",
        },
        headers: ["Origin"],
        queryString: false,
      },
      maxTtl: 31536000,
      minTtl: 0,
      pathPattern: "/content/immutable/*",
      targetOriginId: s3OriginId,
      viewerProtocolPolicy: "redirect-to-https",
    },
    {
      allowedMethods: ["GET", "HEAD", "OPTIONS"],
      cachedMethods: ["GET", "HEAD"],
      compress: true,
      defaultTtl: 3600,
      forwardedValues: {
        cookies: {
          forward: "none",
        },
        queryString: false,
      },
      maxTtl: 86400,
      minTtl: 0,
      pathPattern: "/content/*",
      targetOriginId: s3OriginId,
      viewerProtocolPolicy: "redirect-to-https",
    },
  ],
  origin: [
    {
      domainName: awsS3BucketB.bucketRegionalDomainName,
      originAccessControlId:
        "${aws_cloudfront_origin_access_control.default.id}",
      originId: s3OriginId,
    },
  ],
  priceClass: "PriceClass_200",
  restrictions: {
    geoRestriction: {
      locations: ["US", "CA", "GB", "DE"],
      restrictionType: "whitelist",
    },
  },
  tags: {
    Environment: "production",
  },
  viewerCertificate: {
    cloudfrontDefaultCertificate: true,
  },
});

The example below creates a CloudFront distribution with an origin group for failover routing:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudfrontDistribution.CloudfrontDistribution(this, "s3_distribution", {
  defaultCacheBehavior: {
    targetOriginId: "groupS3",
  },
  origin: [
    {
      domainName: "${aws_s3_bucket.primary.bucket_regional_domain_name}",
      originId: "primaryS3",
      s3OriginConfig: {
        originAccessIdentity:
          "${aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path}",
      },
    },
    {
      domainName: "${aws_s3_bucket.failover.bucket_regional_domain_name}",
      originId: "failoverS3",
      s3OriginConfig: {
        originAccessIdentity:
          "${aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path}",
      },
    },
  ],
  originGroup: [
    {
      failoverCriteria: {
        statusCodes: [403, 404, 500, 502],
      },
      member: [
        {
          originId: "primaryS3",
        },
        {
          originId: "failoverS3",
        },
      ],
      originId: "groupS3",
    },
  ],
});

CloudFront distribution using managed policies (ex: CachingDisabled):

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const s3OriginId = "myS3Origin";
new aws.cloudfrontDistribution.CloudfrontDistribution(this, "s3_distribution", {
  comment: "Some comment",
  defaultCacheBehavior: {
    allowedMethods: ["GET", "HEAD", "OPTIONS"],
    cachePolicyId: "4135ea2d-6df8-44a3-9df3-4b5a84be39a",
    pathPattern: "/content/*",
    targetOriginId: s3OriginId,
  },
  defaultRootObject: "index.html",
  enabled: true,
  isIpv6Enabled: true,
  origin: [
    {
      domainName: "${aws_s3_bucket.primary.bucket_regional_domain_name}",
      originId: "myS3Origin",
      s3OriginConfig: {
        originAccessIdentity:
          "${aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path}",
      },
    },
  ],
  restrictions: {
    geoRestriction: {
      locations: ["US", "CA", "GB", "DE"],
      restrictionType: "whitelist",
    },
  },
  viewerCertificate: {
    cloudfrontDefaultCertificate: true,
  },
});

Argument Reference

The CloudFront distribution argument layout is a complex structure composed of several sub-resources - these resources are laid out below.

Top-Level Arguments

  • aliases (Optional) - Extra CNAMEs (alternate domain names), if any, for this distribution.
  • comment (Optional) - Any comments you want to include about the distribution.
  • customErrorResponse (Optional) - One or more custom error response elements (multiples allowed).
  • defaultCacheBehavior (Required) - Default cache behavior for this distribution (maximum one). Requires either cachePolicyId (preferred) or forwardedValues (deprecated) be set.
  • defaultRootObject (Optional) - Object that you want CloudFront to return (for example, index.html) when an end user requests the root URL.
  • enabled (Required) - Whether the distribution is enabled to accept end user requests for content.
  • isIpv6Enabled (Optional) - Whether the IPv6 is enabled for the distribution.
  • httpVersion (Optional) - Maximum HTTP version to support on the distribution. Allowed values are http11, http2, http2And3 and http3. The default is http2.
  • loggingConfig (Optional) - The logging configuration that controls how logs are written to your distribution (maximum one).
  • orderedCacheBehavior (Optional) - Ordered list of cache behaviors resource for this distribution. List from top to bottom in order of precedence. The topmost cache behavior will have precedence 0.
  • origin (Required) - One or more origins for this distribution (multiples allowed).
  • originGroup (Optional) - One or more origin_group for this distribution (multiples allowed).
  • priceClass (Optional) - Price class for this distribution. One of priceClassAll, priceClass200, priceClass100.
  • restrictions (Required) - The restriction configuration for this distribution (maximum one).
  • tags - (Optional) A map of tags to assign to the resource. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
  • viewerCertificate (Required) - The SSL configuration for this distribution (maximum one).
  • webAclId (Optional) - Unique identifier that specifies the AWS WAF web ACL, if any, to associate with this distribution. To specify a web ACL created using the latest version of AWS WAF (WAFv2), use the ACL ARN, for example awsWafv2WebAclExampleArn. To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example awsWafWebAclExampleId. The WAF Web ACL must exist in the WAF Global (CloudFront) region and the credentials configuring this argument must have waf:getWebAcl permissions assigned.
  • retainOnDelete (Optional) - Disables the distribution instead of deleting it when destroying the resource through Terraform. If this is set, the distribution needs to be deleted manually afterwards. Default: false.
  • waitForDeployment (Optional) - If enabled, the resource will wait for the distribution status to change from inProgress to deployed. Setting this tofalse will skip the process. Default: true.

Cache Behavior Arguments

  • allowedMethods (Required) - Controls which HTTP methods CloudFront processes and forwards to your Amazon S3 bucket or your custom origin.
  • cachedMethods (Required) - Controls whether CloudFront caches the response to requests using the specified HTTP methods.
  • cachePolicyId (Optional) - Unique identifier of the cache policy that is attached to the cache behavior. If configuring the defaultCacheBehavior either cachePolicyId or forwardedValues must be set.
  • compress (Optional) - Whether you want CloudFront to automatically compress content for web requests that include acceptEncoding:Gzip in the request header (default: false).
  • defaultTtl (Optional) - Default amount of time (in seconds) that an object is in a CloudFront cache before CloudFront forwards another request in the absence of an cacheControlMaxAge or expires header.
  • fieldLevelEncryptionId (Optional) - Field level encryption configuration ID.
  • forwardedValues (Optional, Deprecated use cachePolicyId or originRequestPolicyId instead) - The forwarded values configuration that specifies how CloudFront handles query strings, cookies and headers (maximum one).
  • lambdaFunctionAssociation (Optional) - A config block that triggers a lambda function with specific actions (maximum 4).
  • functionAssociation (Optional) - A config block that triggers a cloudfront function with specific actions (maximum 2).
  • maxTtl (Optional) - Maximum amount of time (in seconds) that an object is in a CloudFront cache before CloudFront forwards another request to your origin to determine whether the object has been updated. Only effective in the presence of cacheControlMaxAge, cacheControlSMaxage, and expires headers.
  • minTtl (Optional) - Minimum amount of time that you want objects to stay in CloudFront caches before CloudFront queries your origin to see whether the object has been updated. Defaults to 0 seconds.
  • originRequestPolicyId (Optional) - Unique identifier of the origin request policy that is attached to the behavior.
  • pathPattern (Required) - Pattern (for example, images/*Jpg) that specifies which requests you want this cache behavior to apply to.
  • realtimeLogConfigArn (Optional) - ARN of the real-time log configuration that is attached to this cache behavior.
  • responseHeadersPolicyId (Optional) - Identifier for a response headers policy.
  • smoothStreaming (Optional) - Indicates whether you want to distribute media files in Microsoft Smooth Streaming format using the origin that is associated with this cache behavior.
  • targetOriginId (Required) - Value of ID for the origin that you want CloudFront to route requests to when a request matches the path pattern either for a cache behavior or for the default cache behavior.
  • trustedKeyGroups (Optional) - List of key group IDs that CloudFront can use to validate signed URLs or signed cookies. See the CloudFront User Guide for more information about this feature.
  • trustedSigners (Optional) - List of AWS account IDs (or self) that you want to allow to create signed URLs for private content. See the CloudFront User Guide for more information about this feature.
  • viewerProtocolPolicy (Required) - Use this element to specify the protocol that users can use to access the files in the origin specified by TargetOriginId when a request matches the path pattern in PathPattern. One of allowAll, httpsOnly, or redirectToHttps.
Forwarded Values Arguments
  • cookies (Required) - The forwarded values cookies that specifies how CloudFront handles cookies (maximum one).
  • headers (Optional) - Headers, if any, that you want CloudFront to vary upon for this cache behavior. Specify * to include all headers.
  • queryString (Required) - Indicates whether you want CloudFront to forward query strings to the origin that is associated with this cache behavior.
  • queryStringCacheKeys (Optional) - When specified, along with a value of true for queryString, all query strings are forwarded, however only the query string keys listed in this argument are cached. When omitted with a value of true for queryString, all query string keys are cached.
Lambda Function Association

Lambda@Edge allows you to associate an AWS Lambda Function with a predefined event. You can associate a single function per event type. See What is Lambda@Edge for more information.

Example configuration:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudfrontDistribution.CloudfrontDistribution(this, "example", {
  orderedCacheBehavior: [
    {
      lambdaFunctionAssociation: [
        {
          eventType: "viewer-request",
          includeBody: false,
          lambdaArn: "${aws_lambda_function.example.qualified_arn}",
        },
      ],
    },
  ],
});
  • eventType (Required) - Specific event to trigger this function. Valid values: viewerRequest, originRequest, viewerResponse, originResponse.
  • lambdaArn (Required) - ARN of the Lambda function.
  • includeBody (Optional) - When set to true it exposes the request body to the lambda function. Defaults to false. Valid values: true, false.
Function Association

With CloudFront Functions in Amazon CloudFront, you can write lightweight functions in JavaScript for high-scale, latency-sensitive CDN customizations. You can associate a single function per event type. See CloudFront Functions for more information.

Example configuration:

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudfrontDistribution.CloudfrontDistribution(this, "example", {
  orderedCacheBehavior: [
    {
      functionAssociation: [
        {
          eventType: "viewer-request",
          functionArn: "${aws_cloudfront_function.example.arn}",
        },
      ],
    },
  ],
});
  • eventType (Required) - Specific event to trigger this function. Valid values: viewerRequest or viewerResponse.
  • functionArn (Required) - ARN of the CloudFront function.
Cookies Arguments
  • forward (Required) - Whether you want CloudFront to forward cookies to the origin that is associated with this cache behavior. You can specify all, none or whitelist. If whitelist, you must include the subsequent whitelistedNames.
  • whitelistedNames (Optional) - If you have specified whitelist to forward, the whitelisted cookies that you want CloudFront to forward to your origin.

Custom Error Response Arguments

  • errorCachingMinTtl (Optional) - Minimum amount of time you want HTTP error codes to stay in CloudFront caches before CloudFront queries your origin to see whether the object has been updated.
  • errorCode (Required) - 4xx or 5xx HTTP status code that you want to customize.
  • responseCode (Optional) - HTTP status code that you want CloudFront to return with the custom error page to the viewer.
  • responsePagePath (Optional) - Path of the custom error page (for example, /custom404Html).

Default Cache Behavior Arguments

The arguments for defaultCacheBehavior are the same as for orderedCacheBehavior, except for the pathPattern argument should not be specified.

Logging Config Arguments

  • bucket (Required) - Amazon S3 bucket to store the access logs in, for example, myawslogbucketS3AmazonawsCom.
  • includeCookies (Optional) - Whether to include cookies in access logs (default: false).
  • prefix (Optional) - Prefix to the access log filenames for this distribution, for example, myprefix/.

Origin Arguments

  • connectionAttempts (Optional) - Number of times that CloudFront attempts to connect to the origin. Must be between 1-3. Defaults to 3.
  • connectionTimeout (Optional) - Number of seconds that CloudFront waits when trying to establish a connection to the origin. Must be between 1-10. Defaults to 10.
  • customOriginConfig - The CloudFront custom origin configuration information. If an S3 origin is required, use originAccessControlId or s3OriginConfig instead.
  • domainName (Required) - DNS domain name of either the S3 bucket, or web site of your custom origin.
  • customHeader (Optional) - One or more sub-resources with name and value parameters that specify header data that will be sent to the origin (multiples allowed).
  • originAccessControlId (Optional) - Unique identifier of a CloudFront origin access control for this origin.
  • originId (Required) - Unique identifier for the origin.
  • originPath (Optional) - Optional element that causes CloudFront to request your content from a directory in your Amazon S3 bucket or your custom origin.
  • originShield - The CloudFront Origin Shield configuration information. Using Origin Shield can help reduce the load on your origin. For more information, see Using Origin Shield in the Amazon CloudFront Developer Guide.
  • s3OriginConfig - The CloudFront S3 origin configuration information. If a custom origin is required, use customOriginConfig instead.
Custom Origin Config Arguments
  • httpPort (Required) - HTTP port the custom origin listens on.
  • httpsPort (Required) - HTTPS port the custom origin listens on.
  • originProtocolPolicy (Required) - Origin protocol policy to apply to your origin. One of httpOnly, httpsOnly, or matchViewer.
  • originSslProtocols (Required) - SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPS. A list of one or more of ssLv3, tlSv1, tlSv11, and tlSv12.
  • originKeepaliveTimeout - (Optional) The Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.
  • originReadTimeout - (Optional) The Custom Read timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.
Origin Shield Arguments
  • enabled (Required) - Whether Origin Shield is enabled.
  • originShieldRegion (Required) - AWS Region for Origin Shield. To specify a region, use the region code, not the region name. For example, specify the US East (Ohio) region as us-east-2.
S3 Origin Config Arguments

Origin Group Arguments

  • originId (Required) - Unique identifier for the origin group.
  • failoverCriteria (Required) - The failover criteria for when to failover to the secondary origin.
  • member (Required) - Ordered member configuration blocks assigned to the origin group, where the first member is the primary origin. You must specify two members.
Failover Criteria Arguments
  • statusCodes (Required) - List of HTTP status codes for the origin group.
Member Arguments
  • originId (Required) - Unique identifier of the member origin.

Restrictions Arguments

The restrictions sub-resource takes another single sub-resource named geoRestriction (see the example for usage).

The arguments of geoRestriction are:

  • locations (Required) - ISO 3166-1-alpha-2 codes for which you want CloudFront either to distribute your content (whitelist) or not distribute your content (blacklist). If the type is specified as none an empty array can be used.
  • restrictionType (Required) - Method that you want to use to restrict distribution of your content by country: none, whitelist, or blacklist.

Viewer Certificate Arguments

  • acmCertificateArn - ARN of the AWS Certificate Manager certificate that you wish to use with this distribution. Specify this, cloudfrontDefaultCertificate, or iamCertificateId. The ACM certificate must be in US-EAST-1.
  • cloudfrontDefaultCertificate - true if you want viewers to use HTTPS to request your objects and you're using the CloudFront domain name for your distribution. Specify this, acmCertificateArn, or iamCertificateId.
  • iamCertificateId - IAM certificate identifier of the custom viewer certificate for this distribution if you are using a custom domain. Specify this, acmCertificateArn, or cloudfrontDefaultCertificate.
  • minimumProtocolVersion - Minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. Can only be set if cloudfrontDefaultCertificate =False. See all possible values in this table under "Security policy." Some examples include: tlSv122019 and tlSv122021. Default: tlSv1. NOTE: If you are using a custom certificate (specified with acmCertificateArn or iamCertificateId), and have specified sniOnly in sslSupportMethod, tlSv1 or later must be specified. If you have specified vip in sslSupportMethod, only ssLv3 or tlSv1 can be specified. If you have specified cloudfrontDefaultCertificate, tlSv1 must be specified.
  • sslSupportMethod - How you want CloudFront to serve HTTPS requests. One of vip or sniOnly. Required if you specify acmCertificateArn or iamCertificateId. NOTE: vip causes CloudFront to use a dedicated IP address and may incur extra charges.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • id - Identifier for the distribution. For example: edfdvbd632Bhds5.
  • arn - ARN for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/edfdvbd632Bhds5, where 123456789012 is your AWS account ID.
  • callerReference - Internal value used by CloudFront to allow future updates to the distribution configuration.
  • status - Current status of the distribution. deployed if the distribution's information is fully propagated throughout the Amazon CloudFront system.
  • tagsAll - Map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.
  • trustedKeyGroups - List of nested attributes for active trusted key groups, if the distribution is set up to serve private content with signed URLs.
  • enabled - true if any of the key groups have public keys that CloudFront can use to verify the signatures of signed URLs and signed cookies.
  • items - List of nested attributes for each key group.
    • keyGroupId - ID of the key group that contains the public keys.
    • keyPairIds - Set of CloudFront key pair IDs.
  • trustedSigners - List of nested attributes for active trusted signers, if the distribution is set up to serve private content with signed URLs.
  • enabled - true if any of the AWS accounts listed as trusted signers have active CloudFront key pairs
  • items - List of nested attributes for each trusted signer
    • awsAccountNumber - AWS account ID or self
    • keyPairIds - Set of active CloudFront key pairs associated with the signer account
  • domainName - Domain name corresponding to the distribution. For example: d604721Fxaaqy9CloudfrontNet.
  • lastModifiedTime - Date and time the distribution was last modified.
  • inProgressValidationBatches - Number of invalidation batches currently in progress.
  • etag - Current version of the distribution's information. For example: e2Qwruhapomqzl.
  • hostedZoneId - CloudFront Route 53 zone ID that can be used to route an Alias Resource Record Set to. This attribute is simply an alias for the zone ID z2Fdtndataqyw2.

Import

CloudFront Distributions can be imported using the id, e.g.,

$ terraform import aws_cloudfront_distribution.distribution E74FTE3EXAMPLE