Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 4 additions & 4 deletions docs/deploy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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은 따로 강조하고 멈춘다.

Expand Down Expand Up @@ -280,7 +280,7 @@ sequenceDiagram

- **일찍 전환하는 이유**: 전환해도 남은 크레딧은 만료일까지 그대로 쓰여 일찍 바꿔도 손해가 없다. 무료 플랜의 서비스·인스턴스 종류 제한도 풀려, 출시 직전에 제한에 걸리는 일을 막는다.

1. 콘솔에서 유료 플랜으로 전환(손작업, 버튼 한 번).
1. 콘솔에서 유료 플랜으로 전환(손작업, 버튼 한 번). **2026-11-16 전환 완료**(전환 시점 남은 크레딧 $117).
2. 예산 경보(크레딧 제외 기준)가 정상인지 확인한다.
3. 리소스는 그대로다. 코드 변경 없음.

Expand Down Expand Up @@ -344,15 +344,15 @@ 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 |
| SecureString 실제 값 입력(앱 DB 비밀번호, JWT, 본문 키, 구글 비밀, AI 키), 본문 키 별도 보관 | RDS·파라미터 생성 후 | #91 |
| GitHub 환경 `prod` 생성, `main` 브랜치 생성·보호 | 배포 워크플로 전 | #93 |
| 첫 푸시 뒤 GHCR 패키지 공개로 변경 | 첫 배포 | #93 |
| 디스코드 웹훅 생성·등록 | 알림 작업 | #95 |
| 유료 플랜 전환 | 출시 전 (#94 작업 전) | #94 |
| 유료 플랜 전환 | 출시 전 (#94 작업 전). **2026-11-16 완료** | #94 |
| 출시 전환 절차 실행, `prod` 승인자 켜기 | 출시일 | #94 |

## 13. 구현 이슈
Expand Down
29 changes: 29 additions & 0 deletions infra/terraform/bootstrap/.terraform.lock.hcl

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

109 changes: 109 additions & 0 deletions infra/terraform/bootstrap/README.md
Original file line number Diff line number Diff line change
@@ -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개와 메일 주소를 확인하고, `[email protected]`이 스팸으로 가지 않게 허용해 둔다.

## 본체에서 쓰는 법 (#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`
38 changes: 38 additions & 0 deletions infra/terraform/bootstrap/budget.tf
Original file line number Diff line number Diff line change
@@ -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]
}
}
14 changes: 14 additions & 0 deletions infra/terraform/bootstrap/outputs.tf
Original file line number Diff line number Diff line change
@@ -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
}
11 changes: 11 additions & 0 deletions infra/terraform/bootstrap/providers.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
provider "aws" {
region = var.region

default_tags {
tags = {
project = "sniptext"
env = "prod"
"managed-by" = "terraform"
}
}
}
102 changes: 102 additions & 0 deletions infra/terraform/bootstrap/state_bucket.tf
Original file line number Diff line number Diff line change
@@ -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]
}
5 changes: 5 additions & 0 deletions infra/terraform/bootstrap/terraform.tfvars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# 복사해서 terraform.tfvars로 쓴다 (terraform.tfvars는 커밋하지 않는다)
# budget_email은 여기에 쓰지 않고 환경 변수 TF_VAR_budget_email로 넣는다

region = "ap-northeast-2"
budget_limit_usd = 60
Loading
Loading