클라우드 프론트(CloudFront)
# 새 버킷 생성
resource "aws_s3_bucket" "bucket_2" {
bucket = "${var.prefix}-bucket-${var.nickname}-2"
tags = {
Name = "${var.prefix}-bucket-${var.nickname}-2"
}
}
# 템플릿 데이터 소스 생성
data "template_file" "template_file_1" {
template = "Hello"
}
resource "aws_s3_object" "object" {
bucket = aws_s3_bucket.bucket_2.id
key = "public/index.html"
content = data.template_file.template_file_1.rendered
content_type = "text/html" # 콘텐츠 유형
etag = md5(data.template_file.template_file_1.rendered)
depends_on = [aws_s3_bucket.bucket_2]
}
# CloudFront access control
resource "aws_cloudfront_origin_access_control" "oac_1" {
name = "oac-1"
description = ""
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
resource "aws_cloudfront_distribution" "cd_1" {
enabled = true # CloudFront 배포 활성화
restrictions {
geo_restriction {
restriction_type = "none" # 지리 제약을 설정하지 않음 => 전세계적으로 제공
}
}
default_cache_behavior {
allowed_methods = ["GET", "HEAD", "OPTIONS"]
cached_methods = ["GET", "HEAD", "OPTIONS"]
target_origin_id = "origin_id_1"
forwarded_values {
query_string = false
cookies {
forward = "none"
}
}
viewer_protocol_policy = "redirect-to-https"
}
origin {
domain_name = aws_s3_bucket.bucket_2.bucket_regional_domain_name
origin_path = "/public" # /public 폴더에 있는 리소스만 공개
origin_id = "origin_id_1"
origin_access_control_id = aws_cloudfront_origin_access_control.oac_1.id
}
viewer_certificate {
cloudfront_default_certificate = true # 기본 CloudFront 인증서 사용
}
}
data "aws_iam_policy_document" "bucket_2_policy_1_statement" {
statement {
actions = ["s3:GetObject"] # S3 GetObject 작업을 수행하는 권한을 지정
resources = ["${aws_s3_bucket.bucket_2.arn}/*"]
principals {
type = "Service"
identifiers = ["cloudfront.amazonaws.com"] # CloudFront 서비스에 대한 액세스 지정
}
condition {
test = "StringEquals"
variable = "AWS:SourceArn"
values = [aws_cloudfront_distribution.cd_1.arn]
}
}
}
resource "aws_s3_bucket_policy" "bucket_2_policy_1" {
bucket = aws_s3_bucket.bucket_2.id
policy = data.aws_iam_policy_document.bucket_2_policy_1_statement.json
}