# AWS CloudFront 배포 가이드 ## 📋 프로젝트 개요 AWS CloudFront CDN을 OpenTofu(Terraform fork)로 구성하여 `origin.servidor.it.com`을 origin으로 사용하는 인프라스트럭처 프로젝트입니다. ## 🏗️ 현재 인프라 상태 ### CloudFront Distribution - **Distribution ID**: E1XR8P4ENGP8RU - **CloudFront URL**: https://dspki4yrh5oy1.cloudfront.net - **Origin**: origin.servidor.it.com (HTTP-only) - **Status**: ✅ Deployed and Working ### 보안 설정 - **WAF**: AWS WAF v2 활성화 - WAF ID: d21d84c1-edb9-40af-9cdd-27f42f09c499 - Rate Limiting: 10,000 requests/5min per IP - AWS Managed Rules - Common Rule Set (SQL Injection, XSS 방어) - AWS Managed Rules - Known Bad Inputs (악성 패턴 차단) - **Viewer Protocol**: HTTPS (redirect-to-https) - **Origin Protocol**: HTTP-only (중요: HTTPS 사용 시 504 에러) ### 로깅 및 상태 관리 - **CloudFront Logs**: `s3://aws-cf-cloudfront-logs-535294143817/cloudfront-logs/` - **Terraform State**: `s3://aws-cf-terraform-state-535294143817/aws-cf/terraform.tfstate` - **State Locking**: 비활성화 (DynamoDB 권한 없음) ## 🚀 배포 방법 ### 사전 요구사항 - OpenTofu 또는 Terraform 설치 - AWS CLI 구성 - 필요한 IAM 권한: - CloudFrontFullAccess - S3FullAccess - Route53FullAccess - AWSCertificateManagerFullAccess - AWSWAFFullAccess (WAFv2 포함) - AWSCloudFormationFullAccess ### 초기 설정 ```bash # S3 Backend 설정 (이미 완료됨) ./setup-backend.sh # State 마이그레이션 (이미 완료됨) echo "yes" | tofu init -migrate-state ``` ### 배포 명령어 ```bash # 초기화 tofu init # 계획 확인 tofu plan # 배포 실행 tofu apply -auto-approve # 상태 확인 tofu state list ``` ## 📁 프로젝트 구조 ``` aws-cf/ ├── main.tf # CloudFront 메인 구성 ├── variables.tf # 변수 정의 ├── terraform.tfvars # 변수 값 설정 ├── outputs.tf # 출력 정의 ├── versions.tf # Provider 버전 관리 ├── backend.tf # S3 Backend 설정 ├── security.tf # WAF 및 보안 그룹 ├── acm.tf # ACM 인증서 (비활성화) ├── setup-backend.sh # S3 Backend 설정 스크립트 ├── README.md # 기존 문서 └── DEPLOYMENT_GUIDE.md # 이 문서 ``` ## ⚙️ 중요 설정 내용 ### terraform.tfvars 핵심 설정 ```hcl # Origin 설정 (매우 중요) origin_domain = "origin.servidor.it.com" origin_protocol_policy = "http-only" # HTTPS 사용 시 504 에러! # CloudFront 설정 viewer_protocol_policy = "redirect-to-https" price_class = "PriceClass_100" # 보안 설정 enable_waf = true # 로깅 설정 enable_cloudfront_logging = true cloudfront_logs_bucket = "aws-cf-cloudfront-logs-535294143817" # 비활성화된 기능 (권한/제한 사항) create_route53_records = false # CAA 제한으로 비활성화 create_acm_certificate = false # CloudFront 기본 인증서 사용 enable_cloudformation_stack = false # CloudFormation 권한 없음 ``` ## 🔧 문제 해결 히스토리 ### 1. 504 Gateway Timeout 해결 ✅ **문제**: CloudFront가 origin 서버에 연결할 수 없음 **원인**: origin.servidor.it.com이 HTTP(80)만 지원하는데 HTTPS(443)로 연결 시도 **해결**: ```hcl origin_protocol_policy = "http-only" ``` ### 2. ACM 인증서 CAA 제한 ✅ **문제**: *.servidor.it.com 도메인에 대한 ACM 인증서 발급 실패 **원인**: CAA DNS 레코드가 AWS 인증서 발급을 제한 **해결**: CloudFront 기본 인증서 사용 ```hcl create_acm_certificate = false viewer_certificate { cloudfront_default_certificate = true } ``` ### 3. DynamoDB State Locking 권한 ✅ **문제**: Terraform state locking을 위한 DynamoDB 테이블 생성/접근 불가 **해결**: S3만 사용 (1인 개발 시 충분) ```hcl backend "s3" { bucket = "aws-cf-terraform-state-535294143817" key = "aws-cf/terraform.tfstate" # dynamodb_table = "terraform-state-lock" # 비활성화 } ``` ### 4. 중복 CloudFront Distribution 정리 ✅ **문제**: 여러 배포 시도로 3개의 distribution 생성 **해결**: - E18GW141CX7I8C - 비활성화 중 (삭제 예정) - E32FD742KMW2YY - 비활성화 중 (삭제 예정) - E1XR8P4ENGP8RU - 현재 사용 중 ✅ ### 5. WAF 권한 문제 ✅ **초기 문제**: WAFv2 권한 없다고 오류 발생 **해결**: AWSWAFFullAccess 정책에 wafv2:* 권한 포함되어 있음 확인 ## 📊 모니터링 및 관리 ### 상태 확인 명령어 ```bash # CloudFront 상태 aws cloudfront get-distribution --id E1XR8P4ENGP8RU \ --query 'Distribution.Status' --output text # WAF 연결 확인 aws cloudfront get-distribution --id E1XR8P4ENGP8RU \ --query 'Distribution.DistributionConfig.WebACLId' --output text # 로그 확인 aws s3 ls s3://aws-cf-cloudfront-logs-535294143817/cloudfront-logs/ --recursive # State 파일 확인 aws s3 ls s3://aws-cf-terraform-state-535294143817/aws-cf/ ``` ### 성능 테스트 ```bash # CloudFront 응답 확인 curl -I https://dspki4yrh5oy1.cloudfront.net # 출력 예시: # HTTP/2 200 # content-type: text/html # x-cache: Miss from cloudfront (첫 요청) / Hit from cloudfront (캐시된 요청) ``` ### 비활성화된 Distribution 삭제 (완전 비활성화 후) ```bash # 상태 확인 aws cloudfront list-distributions \ --query 'DistributionList.Items[*].[Id,Status,DistributionConfig.Enabled]' \ --output table # 삭제 (Deployed 상태에서 Enabled=false 일 때) aws cloudfront get-distribution-config --id E18GW141CX7I8C > dist-config.json ETAG=$(jq -r '.ETag' dist-config.json) aws cloudfront delete-distribution --id E18GW141CX7I8C --if-match $ETAG ``` ## 🔒 보안 고려사항 1. **WAF 설정** - 현재 기본 AWS Managed Rules 사용 - 필요시 커스텀 룰 추가 가능 - Rate limiting 조정 가능 (security.tf) 2. **Origin 보안** - ⚠️ Origin이 HTTP만 지원하므로 CloudFront-Origin 간 트래픽 암호화 안됨 - 권장: Origin 서버에 HTTPS 지원 추가 3. **로그 관리** - CloudFront 로그 90일 자동 삭제 설정 - 장기 보관 필요시 S3 lifecycle 수정 ## 📝 향후 개선 사항 ### 권한 획득 시 활성화 가능한 기능 1. **DynamoDB State Locking** - 팀 협업 시 필수 - backend.tf에서 주석 해제 2. **Custom Domain with ACM** - CAA 레코드 수정 후 가능 - terraform.tfvars에서 `create_acm_certificate = true` 3. **CloudFormation Stack** - VPC 및 네트워킹 리소스 관리 - terraform.tfvars에서 `enable_cloudformation_stack = true` ### 성능 최적화 1. Cache Policy 최적화 2. Origin Request Policy 조정 3. CloudFront Edge Location 선택 (Price Class) ## 🏷️ 태그 및 메타데이터 - **Project**: aws-cf - **Environment**: dev - **ManagedBy**: OpenTofu - **Owner**: kaffa - **Created**: 2025-09-08 - **LastUpdated**: 2025-09-09 ## 📚 참고 자료 - [OpenTofu Documentation](https://opentofu.org/docs/) - [AWS CloudFront Best Practices](https://docs.aws.amazon.com/cloudfront/latest/developerguide/best-practices.html) - [AWS WAF Documentation](https://docs.aws.amazon.com/waf/latest/developerguide/) --- *이 문서는 실제 배포 경험을 바탕으로 작성되었습니다.*