Created
May 1, 2022 05:41
-
-
Save anilchalissery/846a498e2602a4b96b23544477dc34ea to your computer and use it in GitHub Desktop.
s3-cloudfront/main.tf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#creating s3 bucket | |
resource "aws_s3_bucket" "s3-bucket" { | |
bucket = "${var.environment}-${var.name}" | |
acl = "private" | |
tags = { | |
Name = "${var.environment}-${var.name}" | |
Environment = var.environment | |
} | |
} | |
# creating s3 bucket policy | |
data "aws_iam_policy_document" "s3-bucket" { | |
statement { | |
actions = ["s3:GetObject"] | |
resources = ["${aws_s3_bucket.s3-bucket.arn}/*"] | |
principals { | |
type = "AWS" | |
identifiers = [aws_cloudfront_origin_access_identity.s3-bucket.iam_arn] | |
} | |
} | |
statement { | |
actions = ["s3:ListBucket"] | |
resources = [aws_s3_bucket.s3-bucket.arn] | |
principals { | |
type = "AWS" | |
identifiers = [aws_cloudfront_origin_access_identity.s3-bucket.iam_arn] | |
} | |
} | |
} | |
#attaching bucket policy | |
resource "aws_s3_bucket_policy" "s3-bucket" { | |
bucket = aws_s3_bucket.s3-bucket.id | |
policy = data.aws_iam_policy_document.s3-bucket.json | |
} | |
#creating cloudfront access identity | |
resource "aws_cloudfront_origin_access_identity" "s3-bucket" { | |
comment = "origin identity for ${var.environment}-${var.name}" | |
} | |
#creating cloudfront distribution | |
resource "aws_cloudfront_distribution" "s3-bucket" { | |
origin { | |
domain_name = aws_s3_bucket.s3-bucket.bucket_regional_domain_name | |
origin_id = "${var.environment}-${var.name}" | |
s3_origin_config { | |
origin_access_identity = aws_cloudfront_origin_access_identity.s3-bucket.cloudfront_access_identity_path | |
} | |
} | |
enabled = true | |
is_ipv6_enabled = true | |
default_root_object = var.root_object | |
wait_for_deployment = false | |
aliases = [var.domain] | |
default_cache_behavior { | |
allowed_methods = ["GET", "HEAD"] | |
cached_methods = ["GET", "HEAD"] | |
target_origin_id = "${var.environment}-${var.name}" | |
forwarded_values { | |
query_string = false | |
cookies { | |
forward = "none" | |
} | |
} | |
min_ttl = 0 | |
default_ttl = 86400 | |
max_ttl = 31536000 | |
compress = true | |
viewer_protocol_policy = "redirect-to-https" | |
} | |
restrictions { | |
geo_restriction { | |
restriction_type = "none" | |
} | |
} | |
custom_error_response { | |
error_code = 404 | |
response_page_path = "/index.html" | |
response_code = 200 | |
} | |
tags = { | |
Environment = var.environment | |
} | |
viewer_certificate { | |
acm_certificate_arn = var.acm | |
#minimum_protocol_version = "TLSv1.2_2021" | |
ssl_support_method = "sni-only" | |
#cloudfront_default_certificate = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment