S3のバケットをオリジンにしてCloudFrontで配信する構成の際にCORSの設定をTerraformで行う方法のまとめ。 ちなみに、Terraformではなくマネジメントコンソールから設定する場合は以下のQiitaの記事がわかりやすくておすすめです。
S3バケットにCORS設定を追加
オリジンにする『aws_s3_bucket』リソースにCORSの設定を追加します。
- 以下、『https://kleinblog.net』からのクロスオリジンを許可する例
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
# オリジンのS3にCORSの設定を追加 | |
resource "aws_s3_bucket" "origin_bucket" { | |
bucket = "origin_bucket" | |
acl = "public-read" | |
# ここに追加 | |
cors_rule { | |
allowed_headers = ["*"] | |
allowed_methods = ["GET", "HEAD"] | |
allowed_origins = ["https://kleinblog.net"] | |
max_age_seconds = 0 | |
} | |
} |
CloudFrontのWhitelist Headersに『Origin』を追加
CloudFrontのホワイトリストにOriginを追加します。
- キャッシュ設定のforwarded_valuesに書く
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
# CloudFrontにヘッダー転送を追加 | |
resource "aws_cloudfront_distribution" "distribution" { | |
origin { | |
domain_name = "${aws_s3_bucket.origin_bucket.bucket_regional_domain_name}" | |
origin_id = "origin_bucket_id" | |
s3_origin_config { | |
origin_access_identity = "origin-access-identity/cloudfront/ABCDEFG1234567" | |
} | |
} | |
enabled = true | |
default_cache_behavior { | |
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] | |
cached_methods = ["GET", "HEAD"] | |
target_origin_id = "${local.s3_origin_id}" | |
forwarded_values { | |
query_string = false | |
# ここにOriginを追加 | |
headers = ["Origin"] | |
cookies { | |
forward = "none" | |
} | |
} | |
viewer_protocol_policy = "allow-all" | |
min_ttl = 0 | |
default_ttl = 3600 | |
max_ttl = 86400 | |
} | |
} |