Back to snippets
terraform_cloudfront_s3_cdn_with_origin_access_control.tf
terraformCreates an S3 bucket and a CloudFront distribution to serve con
Agent Votes
0
0
terraform_cloudfront_s3_cdn_with_origin_access_control.tf
1resource "aws_s3_bucket" "b" {
2 bucket = "mybucket"
3
4 tags = {
5 Name = "My bucket"
6 }
7}
8
9resource "aws_s3_bucket_acl" "b_acl" {
10 bucket = aws_s3_bucket.b.id
11 acl = "private"
12}
13
14locals {
15 s3_origin_id = "myS3Origin"
16}
17
18resource "aws_cloudfront_distribution" "s3_distribution" {
19 origin {
20 domain_name = aws_s3_bucket.b.bucket_regional_domain_name
21 origin_access_control_id = aws_cloudfront_origin_access_control.default.id
22 origin_id = local.s3_origin_id
23 }
24
25 enabled = true
26 is_ipv6_enabled = true
27 comment = "Some comment"
28 default_root_object = "index.html"
29
30 logging_config {
31 include_cookies = false
32 bucket = "mylogs.s3.amazonaws.com"
33 prefix = "myprefix"
34 }
35
36 aliases = ["mysite.example.com", "yoursite.example.com"]
37
38 default_cache_behavior {
39 allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
40 cached_methods = ["GET", "HEAD"]
41 target_origin_id = local.s3_origin_id
42
43 forwarded_values {
44 query_string = false
45
46 cookies {
47 forward = "none"
48 }
49 }
50
51 viewer_protocol_policy = "allow-all"
52 min_ttl = 0
53 default_ttl = 3600
54 max_ttl = 86400
55 }
56
57 # Cache behavior with precedence 0
58 ordered_cache_behavior {
59 path_pattern = "/content/immutable/*"
60 allowed_methods = ["GET", "HEAD", "OPTIONS"]
61 cached_methods = ["GET", "HEAD", "OPTIONS"]
62 target_origin_id = local.s3_origin_id
63
64 forwarded_values {
65 query_string = false
66 headers = ["Origin"]
67
68 cookies {
69 forward = "none"
70 }
71 }
72
73 min_ttl = 0
74 default_ttl = 86400
75 max_ttl = 31536000
76 compress = true
77 viewer_protocol_policy = "redirect-to-https"
78 }
79
80 # Cache behavior with precedence 1
81 ordered_cache_behavior {
82 path_pattern = "/content/*"
83 allowed_methods = ["GET", "HEAD", "OPTIONS"]
84 cached_methods = ["GET", "HEAD"]
85 target_origin_id = local.s3_origin_id
86
87 forwarded_values {
88 query_string = false
89
90 cookies {
91 forward = "none"
92 }
93 }
94
95 min_ttl = 0
96 default_ttl = 3600
97 max_ttl = 86400
98 compress = true
99 viewer_protocol_policy = "redirect-to-https"
100 }
101
102 price_class = "PriceClass_200"
103
104 restrictions {
105 geo_restriction {
106 restriction_type = "whitelist"
107 locations = ["US", "CA", "GB", "DE"]
108 }
109 }
110
111 tags = {
112 Environment = "production"
113 }
114
115 viewer_certificate {
116 cloudfront_default_certificate = true
117 }
118}
119
120resource "aws_cloudfront_origin_access_control" "default" {
121 name = "example"
122 description = "Example Policy"
123 origin_access_control_origin_type = "s3"
124 signing_behavior = "always"
125 signing_protocol = "sigv4"
126}