aws-cloudformation-cloudfront
This AWS CloudFormation skill provides templates and patterns for deploying CloudFront CDN distributions with support for multiple origin types including S3, ALB, API Gateway, and Lambda@Edge. Use it when building production-ready content delivery infrastructure, configuring complex caching strategies across multiple origins, implementing security headers and WAF integration, or managing custom domains with ACM certificates in CloudFormation templates.
git clone --depth 1 https://github.com/giuseppe-trisciuoglio/developer-kit /tmp/aws-cloudformation-cloudfront && cp -r /tmp/aws-cloudformation-cloudfront/plugins/developer-kit-aws/skills/aws-cloudformation/aws-cloudformation-cloudfront ~/.claude/skills/aws-cloudformation-cloudfrontSKILL.md
# AWS CloudFormation CloudFront CDN
## Overview
Create production-ready CDN infrastructure using AWS CloudFormation templates. This skill covers CloudFront distributions, multiple origins (ALB, S3, API Gateway, Lambda@Edge, VPC Origins), CacheBehaviors, Functions, SecurityHeaders, and best practices for parameters, outputs, and cross-stack references.
## When to Use
- Creating CloudFront distributions with CloudFormation
- Configuring origins (ALB, S3, Lambda@Edge, VPC Origins) with path patterns
- Implementing caching with CacheBehaviors and Cache Policies
- Configuring custom domains with ACM and SecurityHeaders
- Integrating WAF with CloudFront distributions
## Instructions
Follow these steps to create CloudFront distributions with CloudFormation:
### 1. Define Distribution Parameters
**Validate before deploying:**
```bash
aws cloudformation validate-template --template-body file://template.yaml
cfn-lint template.yaml
```
Specify domain names, ACM certificates, price class, and origin settings:
```yaml
Parameters:
DomainName:
Type: String
Default: cdn.example.com
Description: Custom domain name for CloudFront distribution
CertificateArn:
Type: AWS::ACM::Certificate::Arn
Description: ACM certificate ARN for HTTPS
PriceClass:
Type: String
Default: PriceClass_All
AllowedValues:
- PriceClass_All
- PriceClass_100
- PriceClass_200
Description: CloudFront price class
OriginDomainName:
Type: String
Description: Domain name of the origin (ALB or S3)
```
### 2. Configure Origins
Add S3 buckets, ALBs, API Gateway, or custom origins. For S3 origins, use OAI (legacy) or OAC (recommended):
```yaml
Resources:
# S3 Bucket
StaticBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "static-assets-${AWS::AccountId}-${AWS::Region}"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
# Origin Access Control (recommended)
OriginAccessControl:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: !Sub "${AWS::StackName}-oac"
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
```
### 3. Set Up Default Cache Behavior
Configure viewer request/response policies and caching:
```yaml
Resources:
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- Id: S3Origin
DomainName: !GetAtt StaticBucket.RegionalDomainName
AccessControlId: !Ref OriginAccessControl
S3OriginConfig:
OriginAccessIdentity: ""
DefaultCacheBehavior:
TargetOriginId: S3Origin
ViewerProtocolPolicy: redirect-to-https
AllowedMethods:
- GET
- HEAD
CachedMethods:
- GET
- HEAD
Compress: true
CachePolicyId: !Ref CachePolicy
```
### 4. Add Additional Cache Behaviors
Create path-specific caching rules for different content types:
```yaml
Resources:
ApiCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: !Sub "${AWS::StackName}-api-cache"
DefaultTTL: 300
MaxTTL: 600
MinTTL: 60
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
CacheBehaviors:
- PathPattern: "/api/*"
TargetOriginId: ApiOrigin
CachePolicyId: !GetAtt ApiCachePolicy.Id
AllowedMethods:
- GET
- HEAD
- OPTIONS
- PUT
- POST
```
### 5. Configure Security Settings
Implement security headers and WAF integration:
```yaml
Resources:
SecurityHeadersPolicy:
Type: AWS::CloudFront::ResponseHeadersPolicy
Properties:
ResponseHeadersPolicyConfig:
Name: !Sub "${AWS::StackName}-security-headers"
SecurityHeadersConfig:
StrictTransportSecurity:
AccessControlMaxAgeSec: 31536000
IncludeSubdomains: true
Override: true
FrameOptions:
FrameOption: DENY
Override: true
WAFWebACL:
Type: AWS::WAFv2::WebACL
Properties:
Name: !Sub "${AWS::StackName}-waf"
Scope: CLOUDFRONT
DefaultAction:
Allow: {}
```
### 6. Add CloudFront Functions
Configure functions for request/response manipulation:
```yaml
Resources:
RewritePathFunction:
Type: AWS::CloudFront::Function
Properties:
Name: !Sub "${AWS::StackName}-rewrite-path"
FunctionCode: |
function handler(event) {
var request = event.request;
// Function code here
return request;
}
Runtime: cloudfront-js-1.0
AutoPublish: true
```
### 7. Configure Monitoring
Set up logging and access logs to S3:
```yaml
Resources:
AccessLogsBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "cloudfront-logs-${AWS::AccountId}"
CloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Logging:
Bucket: !Ref AccessLogsBucket
Prefix: cloudfront-logs/
IncludeCookies: false
```
### 8. Create Outputs
Export distribution details for cross-stack references:
```yaml
Outputs:
DistributionDomainName:
Description: CloudFront distribution domain name
Value: !GetAtt CloudFrontDistribution.DomainName
Export:
Name: !Sub "${AWS::StackName}-DistributionDomainName"
DistributionId:
Description: CloudFront distribution ID
Value: !Ref CloudFrontDistribution
Export:
Name: !Sub "${AWS::StackName}-DistributionId"
```
## Best Practices
### Security
- Always use HTTPS with minimum TLS 1.2
- Implement SecurityHeaders with HSTS, XSS protection
- Use WAF for protection agaiProvides chunking strategies for RAG systems. Generates chunk size recommendations (256-1024 tokens), overlap percentages (10-20%), and semantic boundary detection methods. Validates semantic coherence and evaluates retrieval precision/recall metrics. Use when building retrieval-augmented generation systems, vector databases, or processing large documents.
>
Implements document chunking, embedding generation, vector storage, and retrieval pipelines for Retrieval-Augmented Generation systems. Use when building RAG applications, creating document Q&A systems, or integrating AI with knowledge bases.
Provides AWS CloudFormation patterns for Auto Scaling including EC2, ECS, and Lambda. Use when creating Auto Scaling groups, launch configurations, launch templates, scaling policies, lifecycle hooks, and predictive scaling. Covers template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references, and best practices for high availability and cost optimization.
Provides AWS CloudFormation patterns for Amazon Bedrock resources including agents, knowledge bases, data sources, guardrails, prompts, flows, and inference profiles. Use when creating Bedrock agents with action groups, implementing RAG with knowledge bases, configuring vector stores, setting up content moderation guardrails, managing prompts, orchestrating workflows with flows, and configuring inference profiles for model optimization.
Provides AWS CloudFormation patterns for CloudWatch monitoring, metrics, alarms, dashboards, logs, and observability. Use when creating CloudWatch metrics, alarms, dashboards, log groups, log subscriptions, anomaly detection, synthesized canaries, Application Signals, and implementing template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references, and CloudWatch best practices for monitoring production infrastructure.
Provides AWS CloudFormation patterns for DynamoDB tables, GSIs, LSIs, auto-scaling, and streams. Use when creating DynamoDB tables with CloudFormation, configuring primary keys, local/global secondary indexes, capacity modes (on-demand/provisioned), point-in-time recovery, encryption, TTL, and implementing template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references.
Provides AWS CloudFormation patterns for EC2 instances, Security Groups, IAM roles, and load balancers. Use when creating EC2 instances, SPOT instances, Security Groups, IAM roles for EC2, Application Load Balancers (ALB), Target Groups, and implementing template structure with Parameters, Outputs, Mappings, Conditions, and cross-stack references.