diff --git a/.gitignore b/.gitignore index 6069b25..77b9662 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,20 @@ out/ ### 로컬 비밀 값·개인 설정 ### .env CLAUDE.local.md + +### 테라폼 ### +# 상태 파일·작업 폴더·변수 파일은 커밋하지 않는다 (.terraform.lock.hcl은 커밋) +*.tfstate +*.tfstate.* +.terraform/ +*.tfvars +*.tfvars.json +!*.tfvars.example +crash.log +crash.*.log +override.tf +override.tf.json +*_override.tf +*_override.tf.json +*.tfplan +tfplan diff --git a/docs/deploy-design.md b/docs/deploy-design.md index 79be5b0..7c73c0d 100644 --- a/docs/deploy-design.md +++ b/docs/deploy-design.md @@ -142,7 +142,7 @@ sequenceDiagram ### 4-7. 테라폼 상태 저장소 - **고른 것**: `infra/terraform/bootstrap/`이 S3 상태 버킷(버전 관리, 암호화, 공개 차단, 삭제 방지)을 만든다. 잠금은 S3 네이티브 잠금(`use_lockfile`)으로 하고 DynamoDB 테이블은 만들지 않는다. 버킷 이름에 계정 ID를 붙여 계정 이전 시 겹치지 않게 한다. -- **대가**: bootstrap 자체의 상태는 로컬에 둔다(커밋하지 않음). 잃어버리면 import로 되살린다. +- **대가**: bootstrap 자신의 상태도 처음에는 로컬에서 만들고, 버킷이 생긴 뒤 같은 버킷(`bootstrap/terraform.tfstate`)으로 옮긴다. 로컬 파일을 잃을 위험을 없애는 대신, 새로 만들거나 지울 때 로컬로 되돌리는 단계가 하나 붙는다(`infra/terraform/bootstrap/README.md`). - 모든 리소스에 `project=sniptext`, `env=prod`, `managed-by=terraform` 태그를 공급자 `default_tags`로 붙인다. 테라폼·공급자·액션 버전은 고정한다. - 변경 흐름: `fmt` → `validate` → `plan` 요약 보고 → 확인 뒤 `apply`. 삭제·교체가 있는 plan은 따로 강조하고 멈춘다. @@ -280,7 +280,7 @@ sequenceDiagram - **일찍 전환하는 이유**: 전환해도 남은 크레딧은 만료일까지 그대로 쓰여 일찍 바꿔도 손해가 없다. 무료 플랜의 서비스·인스턴스 종류 제한도 풀려, 출시 직전에 제한에 걸리는 일을 막는다. -1. 콘솔에서 유료 플랜으로 전환(손작업, 버튼 한 번). +1. 콘솔에서 유료 플랜으로 전환(손작업, 버튼 한 번). **2026-11-16 전환 완료**(전환 시점 남은 크레딧 $117). 2. 예산 경보(크레딧 제외 기준)가 정상인지 확인한다. 3. 리소스는 그대로다. 코드 변경 없음. @@ -344,7 +344,7 @@ sequenceDiagram | 작업 | 시점 | 이슈 | | --- | --- | --- | | 루트 계정 2단계 인증, 결제 수단 확인 | 시작 전 | #89 | -| bootstrap 최초 실행용 관리자 자격 준비(장기 접근 키 대신 IAM Identity Center 또는 임시 자격) | 시작 전 | #89 | +| bootstrap 최초 실행용 관리자 자격 준비: IAM 사용자 `sniptext-admin`(MFA, 접근 키 없음) + `aws login` 임시 자격. IAM Identity Center는 권한 세트에 AWS Organizations가 필요해 쓰지 않는다(10절) | 시작 전 | #89 | | 예산 경보 구독 메일 확인 | bootstrap 후 | #89 | | 가비아 `sniptext.kr` 네임서버를 Route 53 4개로 변경 | 호스팅 영역 생성 후 | #90 | | 앱 전용 DB 계정 `sniptext_app`·스키마 `sniptext_dev` 생성(SSM 포트 포워딩) | RDS 생성 후 | #91 | @@ -352,7 +352,7 @@ sequenceDiagram | GitHub 환경 `prod` 생성, `main` 브랜치 생성·보호 | 배포 워크플로 전 | #93 | | 첫 푸시 뒤 GHCR 패키지 공개로 변경 | 첫 배포 | #93 | | 디스코드 웹훅 생성·등록 | 알림 작업 | #95 | -| 유료 플랜 전환 | 출시 전 (#94 작업 전) | #94 | +| 유료 플랜 전환 | 출시 전 (#94 작업 전). **2026-11-16 완료** | #94 | | 출시 전환 절차 실행, `prod` 승인자 켜기 | 출시일 | #94 | ## 13. 구현 이슈 diff --git a/infra/terraform/bootstrap/.terraform.lock.hcl b/infra/terraform/bootstrap/.terraform.lock.hcl new file mode 100644 index 0000000..61cd8af --- /dev/null +++ b/infra/terraform/bootstrap/.terraform.lock.hcl @@ -0,0 +1,29 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.73.0" + constraints = "~> 6.0" + hashes = [ + "h1:87t8o/A0y2RE3PtCLx/BiASSrDrKSETYTF9jRvKc7aw=", + "h1:BxY7G1XjRbgyrutM3eVuegtICBS5Zz6YweK1K32Ide8=", + "h1:Jf7FuNLRB9cs3KvwJPMFGmE4C3lvwT/EuvQUo9gdDBc=", + "h1:nNijzz9KWdbzuhfrTQrqT3Bm7KmkhoXonVwAasVXTRg=", + "zh:0f7403264fbfbcad526a5ddb9553be6ab12dba14e5901d0c2ccabc38d9ccf9a0", + "zh:26be4e8afc94ef29c98b8219dc49b19ce21a04d3f2b4e5be6116e9526ece0355", + "zh:2ba661a4a782fba053c411ce4d828dc148d7ed3998d073a28370a559400b1578", + "zh:2c422d0edd37bf7470c84f1d1f76487f30948768878204a65a18189bf878467a", + "zh:49f9d1486d48033d298977f7c288f8bbb22bb246f00926d1cb8b0bb98985451c", + "zh:4f946cf11667e1f3bce53fd5ad92eccf47fafaa1bbaa68c742173db61773a1da", + "zh:70beb5e13ddcdbeecb2a78be2b75d09a0fc6ce7e69b574c84a90924fd4262406", + "zh:8c5b974104ff9a887b29fdb2700cdbb5e6fd2eceef1cc3b28f523beda4fd8dfb", + "zh:9252068667bc6528ee6e83e837f3c2f901756136a33442455d61c6fa34e1160a", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:9d086b792598b43e87502d47c4a3f388465b3a21a6a6b2783e48c89dee1f0543", + "zh:b5e6e77a43c1655285d99145b2cf0cc2da7a6c6ea3531d000cf8cca2c717693b", + "zh:b7ebe893e5ec76b362b61ffb28c67b40d890e0f59f5f2f8829765b16ee3e53b0", + "zh:c8c1e186839ad3cba37b427181af1e62eaf06c6daa5dca29105e1981dfaeb4c2", + "zh:e988377e7aea51e1fefe0b52c78bc725a11327051e20a71f81069191ee077d2d", + "zh:ee9188027919459a48bf9bac8f8f1dd172f5be198b88c2c47789b6daa8bb8bcb", + ] +} diff --git a/infra/terraform/bootstrap/README.md b/infra/terraform/bootstrap/README.md new file mode 100644 index 0000000..8564e2f --- /dev/null +++ b/infra/terraform/bootstrap/README.md @@ -0,0 +1,109 @@ +# 테라폼 bootstrap + +본체 테라폼(`infra/terraform/` 아래, #90~)이 쓸 **상태 저장 버킷**과 **월 예산 경보**를 만든다. 계정마다 한 번만 만든다. + +| 리소스 | 내용 | +| --- | --- | +| S3 `sniptext-tfstate-<계정 ID>` | 버전 관리, SSE-S3 암호화, 공개 차단, HTTPS 아닌 요청 거절, 삭제 방지(`prevent_destroy`), 이전 버전 90일 뒤 정리(최근 10개 유지) | +| Budgets `sniptext-monthly` | 월 $60(크레딧·환불 제외), 실제 80%·100%, 예측 100%에서 메일 | + +- 잠금은 S3 네이티브 잠금(`use_lockfile`)을 쓴다. DynamoDB 테이블은 없다. +- bootstrap 자신의 상태도 이 버킷의 `bootstrap/terraform.tfstate`에 둔다. 로컬 파일을 잃어 테라폼이 리소스를 못 알아보는 일을 막고, 버킷의 버전 관리로 이전 상태도 남는다. +- 상태에는 예산 메일 주소가 들어 있다. 버킷은 공개 차단돼 있지만 상태 파일을 내려받아 공유하지 않는다. +- 버킷 이름에 계정 ID가 들어가 저장소에 쓰지 않고, `init` 때 `-backend-config`로 넘긴다. + +## 준비 + +- 테라폼 1.11 이상, AWS CLI 2.32 이상 +- `sniptext-admin`으로 `aws login --profile sniptext` (장기 접근 키를 만들지 않는다) +- 예산 메일은 환경 변수로만 넣는다: `TF_VAR_budget_email` + +## 변경할 때 (파워셸) + +```powershell +cd infra/terraform/bootstrap + +# 임시 자격을 환경 변수로 꺼낸다 (만료되면 aws login부터 다시) +aws configure export-credentials --profile sniptext --format powershell | Invoke-Expression +$env:AWS_REGION = "ap-northeast-2" +$env:TF_VAR_budget_email = "받을주소@example.com" # 사용자 환경 변수에 있으면 생략 + +$acct = aws sts get-caller-identity --query Account --output text +terraform init "-backend-config=bucket=sniptext-tfstate-$acct" +terraform fmt -check +terraform validate +terraform plan -out tfplan # 결과 확인. 삭제·교체가 있으면 멈춘다 +terraform apply tfplan +``` + +## 새 계정에서 처음 만들 때 + +버킷이 아직 없어 S3 backend로 시작할 수 없다. 로컬 상태로 만든 뒤 버킷으로 옮긴다. + +```powershell +# 1) 이번만 로컬 backend로 덮어쓴다 (*_override.tf는 .gitignore 대상) +Set-Content -Encoding ascii backend_override.tf 'terraform { backend "local" {} }' +terraform init +terraform plan -out tfplan +terraform apply tfplan + +# 2) 덮어쓰기를 지우고 상태를 버킷으로 옮긴다 +Remove-Item backend_override.tf +$acct = aws sts get-caller-identity --query Account --output text +terraform init -migrate-state "-backend-config=bucket=sniptext-tfstate-$acct" +terraform state list # 버킷에서 읽은 목록 확인 +terraform plan # 변경 없음이 나와야 한다 + +# 3) 로컬에 남은 상태 파일을 지운다 (메일 주소가 들어 있다) +Remove-Item terraform.tfstate, terraform.tfstate.backup, tfplan +``` + +apply 뒤 할 일 +- 예산 경보는 구독 확인 메일이 오지 않는다. 콘솔 **Budgets**에서 `sniptext-monthly`의 알림 3개와 메일 주소를 확인하고, `no-reply@budgets.amazonaws.com`이 스팸으로 가지 않게 허용해 둔다. + +## 본체에서 쓰는 법 (#90~) + +```hcl +terraform { + backend "s3" { + key = "prod/terraform.tfstate" + region = "ap-northeast-2" + encrypt = true + use_lockfile = true + } +} +``` + +bootstrap과 같이 `terraform init "-backend-config=bucket=sniptext-tfstate-$acct"`로 버킷을 넘긴다. + +## 공급자 잠금 파일 + +`.terraform.lock.hcl`은 커밋한다. 공급자 버전을 올리면 여러 운영체제 해시를 다시 넣는다. + +```powershell +terraform providers lock -platform=windows_amd64 -platform=linux_amd64 -platform=darwin_arm64 -platform=darwin_amd64 +``` + +## 상태가 망가졌을 때 + +- 잘못된 apply 등으로 상태가 틀어지면 버킷의 이전 버전(`bootstrap/terraform.tfstate`)을 되살린다. +- 상태를 통째로 잃었다면 리소스는 그대로 두고 import로 다시 연결한다. + +```powershell +$bucket = "sniptext-tfstate-<계정 ID>" +terraform import aws_s3_bucket.tfstate $bucket +terraform import aws_s3_bucket_versioning.tfstate $bucket +terraform import aws_s3_bucket_server_side_encryption_configuration.tfstate $bucket +terraform import aws_s3_bucket_public_access_block.tfstate $bucket +terraform import aws_s3_bucket_ownership_controls.tfstate $bucket +terraform import aws_s3_bucket_policy.tfstate $bucket +terraform import aws_s3_bucket_lifecycle_configuration.tfstate $bucket +terraform import aws_budgets_budget.monthly "<계정 ID>:sniptext-monthly" +terraform plan # 변경 없음이 나와야 한다 +``` + +## 지울 때 + +1. 본체(#90~)를 먼저 destroy한다. 본체 상태가 이 버킷에 있다. +2. 상태를 로컬로 되돌린다: `backend_override.tf`(위 절차 1)를 만들고 `terraform init -migrate-state` +3. `state_bucket.tf`의 `prevent_destroy`를 풀고, 버킷 안의 모든 버전을 비운 뒤 `terraform destroy` diff --git a/infra/terraform/bootstrap/budget.tf b/infra/terraform/bootstrap/budget.tf new file mode 100644 index 0000000..a843af8 --- /dev/null +++ b/infra/terraform/bootstrap/budget.tf @@ -0,0 +1,38 @@ +# 월 비용 예산 경보. 실제 80%·100%, 예측 100%에서 메일 +resource "aws_budgets_budget" "monthly" { + name = "sniptext-monthly" + budget_type = "COST" + limit_amount = format("%.1f", var.budget_limit_usd) + limit_unit = "USD" + time_unit = "MONTHLY" + + # 크레딧을 포함하면 차감 후 금액(거의 $0)을 봐서 크레딧 기간에 경보가 울리지 않는다 + cost_types { + include_credit = false + include_refund = false + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 80 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.budget_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 100 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.budget_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 100 + threshold_type = "PERCENTAGE" + notification_type = "FORECASTED" + subscriber_email_addresses = [var.budget_email] + } +} diff --git a/infra/terraform/bootstrap/outputs.tf b/infra/terraform/bootstrap/outputs.tf new file mode 100644 index 0000000..bd27fa8 --- /dev/null +++ b/infra/terraform/bootstrap/outputs.tf @@ -0,0 +1,14 @@ +output "state_bucket_name" { + description = "본체 테라폼(#90~)의 backend \"s3\" bucket 값" + value = aws_s3_bucket.tfstate.bucket +} + +output "region" { + description = "상태 버킷 리전" + value = var.region +} + +output "budget_name" { + description = "예산 이름" + value = aws_budgets_budget.monthly.name +} diff --git a/infra/terraform/bootstrap/providers.tf b/infra/terraform/bootstrap/providers.tf new file mode 100644 index 0000000..566c193 --- /dev/null +++ b/infra/terraform/bootstrap/providers.tf @@ -0,0 +1,11 @@ +provider "aws" { + region = var.region + + default_tags { + tags = { + project = "sniptext" + env = "prod" + "managed-by" = "terraform" + } + } +} diff --git a/infra/terraform/bootstrap/state_bucket.tf b/infra/terraform/bootstrap/state_bucket.tf new file mode 100644 index 0000000..ef6e943 --- /dev/null +++ b/infra/terraform/bootstrap/state_bucket.tf @@ -0,0 +1,102 @@ +data "aws_caller_identity" "current" {} + +# 테라폼 상태 저장 버킷. 계정 ID를 붙여 계정을 옮겨도 이름이 겹치지 않게 한다 +# 잠금은 S3 네이티브 잠금(backend의 use_lockfile)을 쓰므로 DynamoDB 테이블은 만들지 않는다 +resource "aws_s3_bucket" "tfstate" { + bucket = "sniptext-tfstate-${data.aws_caller_identity.current.account_id}" + + lifecycle { + prevent_destroy = true + } +} + +resource "aws_s3_bucket_versioning" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + + versioning_configuration { + status = "Enabled" + } +} + +# SSE-S3(AES256). KMS 고객 관리 키는 월 비용이 붙고 이 규모에서 이득이 없다 +resource "aws_s3_bucket_server_side_encryption_configuration" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_bucket_public_access_block" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +# 암호화되지 않은 연결(HTTP)로 오는 요청은 거절한다 +data "aws_iam_policy_document" "tfstate" { + statement { + sid = "DenyInsecureTransport" + effect = "Deny" + actions = ["s3:*"] + resources = [ + aws_s3_bucket.tfstate.arn, + "${aws_s3_bucket.tfstate.arn}/*", + ] + + principals { + type = "*" + identifiers = ["*"] + } + + condition { + test = "Bool" + variable = "aws:SecureTransport" + values = ["false"] + } + } +} + +resource "aws_s3_bucket_policy" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + policy = data.aws_iam_policy_document.tfstate.json + + # 공개 차단 설정이 먼저 적용된 뒤 정책을 건다 + depends_on = [aws_s3_bucket_public_access_block.tfstate] +} + +# 이전 버전은 최근 10개를 남기고 90일 뒤 지운다. 상태 파일은 작아 비용은 사실상 0이지만 무한히 쌓이지 않게 한다 +resource "aws_s3_bucket_lifecycle_configuration" "tfstate" { + bucket = aws_s3_bucket.tfstate.id + + rule { + id = "expire-old-state-versions" + status = "Enabled" + + filter {} + + noncurrent_version_expiration { + noncurrent_days = 90 + newer_noncurrent_versions = 10 + } + + abort_incomplete_multipart_upload { + days_after_initiation = 7 + } + } + + depends_on = [aws_s3_bucket_versioning.tfstate] +} diff --git a/infra/terraform/bootstrap/terraform.tfvars.example b/infra/terraform/bootstrap/terraform.tfvars.example new file mode 100644 index 0000000..94a6bdb --- /dev/null +++ b/infra/terraform/bootstrap/terraform.tfvars.example @@ -0,0 +1,5 @@ +# 복사해서 terraform.tfvars로 쓴다 (terraform.tfvars는 커밋하지 않는다) +# budget_email은 여기에 쓰지 않고 환경 변수 TF_VAR_budget_email로 넣는다 + +region = "ap-northeast-2" +budget_limit_usd = 60 diff --git a/infra/terraform/bootstrap/variables.tf b/infra/terraform/bootstrap/variables.tf new file mode 100644 index 0000000..197e2fd --- /dev/null +++ b/infra/terraform/bootstrap/variables.tf @@ -0,0 +1,34 @@ +variable "region" { + description = "AWS 리전. backend 블록에는 변수를 쓸 수 없어 versions.tf의 backend region과 같은 값만 허용한다" + type = string + default = "ap-northeast-2" + + # 다른 리전에 버킷을 만들면 backend가 서울에서 버킷을 찾아 상태 이전이 실패한다. + # 리전을 바꾸려면 이 검증과 versions.tf의 backend region을 함께 바꾼다 + validation { + condition = var.region == "ap-northeast-2" + error_message = "region은 versions.tf의 backend region(ap-northeast-2)과 같아야 합니다. 바꾸려면 둘을 함께 바꾸세요." + } +} + +variable "budget_limit_usd" { + description = "월 예산(USD, 크레딧 제외). 예상 운영비 약 $42보다 80% 경보선이 높도록 $60" + type = number + default = 60 + + validation { + condition = var.budget_limit_usd > 0 + error_message = "budget_limit_usd는 0보다 커야 합니다." + } +} + +variable "budget_email" { + description = "예산 경보 받을 메일. 파일에 쓰지 않고 환경 변수 TF_VAR_budget_email로만 넣는다" + type = string + sensitive = true + + validation { + condition = can(regex("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$", var.budget_email)) + error_message = "budget_email 형식이 올바르지 않습니다." + } +} diff --git a/infra/terraform/bootstrap/versions.tf b/infra/terraform/bootstrap/versions.tf new file mode 100644 index 0000000..9f2a7c6 --- /dev/null +++ b/infra/terraform/bootstrap/versions.tf @@ -0,0 +1,22 @@ +terraform { + # 쓰기 전용 인자(*_wo)를 #91에서 쓰므로 모든 루트 모듈을 1.11 이상으로 맞춘다 + required_version = ">= 1.11" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + } + + # bootstrap 자신의 상태도 이 디렉터리가 만든 상태 버킷에 둔다 (로컬 파일을 잃지 않게) + # 버킷 이름에는 계정 ID가 들어가 저장소에 쓰지 않고 init 때 넘긴다: + # terraform init -backend-config="bucket=sniptext-tfstate-<계정 ID>" + # 버킷이 아직 없는 새 계정에서 처음 만들 때는 README "새 계정에서 처음 만들 때" 절차를 따른다 + backend "s3" { + key = "bootstrap/terraform.tfstate" + region = "ap-northeast-2" + encrypt = true + use_lockfile = true + } +}