Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
| --- | --- | --- |
| `ci.yml` | `main` 대상 PR·push | PR dependency graph 제출 후 review, 일반 JUnit, MySQL 통합 테스트, 현재 `Dockerfile` 이미지의 기동·HTTP baseline을 검증하고 `CI / build`에서 집계 |
| `quality.yml` | `main` 대상 PR·push, 수동 실행 | Actionlint, ShellCheck, 미해결 merge marker 검사 |
| `terraform.yml` | PM Terraform 또는 해당 workflow 변경 PR·push, 수동 실행 | Terraform 1.14.8에서 fmt·잠금 파일 기준 provider 초기화·validate. AWS backend 접속이나 apply 없이 실행 |
| `codeql.yml` | `main` 대상 PR·push, 주 1회, 수동 실행 | Java CodeQL 보안 분석 |
| `dependency-submission.yml` | `main` push, 수동 실행 | Gradle 의존성 그래프 제출 |
| `deploy.yml` | `main` push, 수동 실행 | 기존 DockerHub·EC2·Nginx/TLS·smoke·contract 배포 흐름 |
Expand Down
47 changes: 47 additions & 0 deletions .github/workflows/terraform.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Terraform

on:
pull_request:
branches: [main]
paths:
- "infra/terraform-pm/**"
- ".github/workflows/terraform.yml"
push:
branches: [main]
paths:
- "infra/terraform-pm/**"
- ".github/workflows/terraform.yml"
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 10
defaults:
run:
working-directory: infra/terraform-pm
steps:
- name: Checkout source code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

- name: Set up Terraform
uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
with:
terraform_version: 1.14.8
terraform_wrapper: false

- name: Check formatting
run: terraform fmt -check -recursive

- name: Initialize providers without AWS backend access
run: terraform init -backend=false -input=false -lockfile=readonly

- name: Validate configuration
run: terraform validate -no-color
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,16 +247,18 @@ docker compose --env-file .env.production up -d

#### 3) AWS 그린필드 + off-hours 스케줄 (Terraform)

VPC/EC2/RDS/EIP와 개발 off-hours(03:00~12:00 KST) Stop/Start를 Terraform으로 생성합니다.
PM AWS 계정의 VPC/EC2/RDS/EIP, S3/CloudFront와 off-hours(03:00~12:00 KST) Stop/Start를 Terraform으로 관리합니다.

**설정·컷오버·구 리소스 폐기**: [`infra/terraform/README.md`](infra/terraform/README.md)
**현재 운영 설정**: [`infra/terraform-pm/README.md`](infra/terraform-pm/README.md). `infra/terraform`은 이전 계정 정리용 레거시 구성입니다.

```bash
cd infra/terraform
cp terraform.tfvars.example terraform.tfvars # key pair, ssh CIDR, db_password, alert_email
terraform init && terraform apply
cd infra/terraform-pm
# Terraform 1.10+ / afternote-pm 프로필과 운영 terraform.tfvars가 필요합니다.
# init은 PM 계정의 비공개 S3에서 운영 state를 읽습니다.
terraform init
terraform plan
terraform output elastic_ip # DNS A + GitHub EC2_HOST
terraform output jdbc_url_hint # .env.production DB_URL
terraform output jdbc_url_hint # deploy/production.env의 DB_URL
```

### 실행 방법
Expand Down
19 changes: 19 additions & 0 deletions infra/terraform-pm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
.terraform/
.state-migration-backups/
*.tfstate
*.tfstate.*
terraform.tfvars
*.tfplan
*.log
.build/
*.zip
*_override.tf
*_override.tf.json

deploy-key
production.env
previous-production.env
known_hosts
outputs.json
.certbot-email
contract-credentials.json
48 changes: 48 additions & 0 deletions infra/terraform-pm/.terraform.lock.hcl

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

102 changes: 102 additions & 0 deletions infra/terraform-pm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# AfterNote PM 계정 운영 인프라

현재 운영 Terraform 루트입니다. AWS 프로필은 `afternote-pm`, 허용 계정은
`079477842373`, 리전은 서울(`ap-northeast-2`)로 고정합니다.
이전 계정의 `../terraform`과 state를 섞지 않습니다.

2026-11-22 이전과 구 계정의 AfterNote 리소스 정리를 완료했습니다.
운영 리소스 51개와 state 버킷 설정 6개를 관리하며, 이전 계정의 `clog`와 개인 IAM 사용자는 보존했습니다.
배포·스모크·계약 테스트는 [GitHub Actions 실행 결과](https://github.com/Afternote/Afternote-BE/actions/runs/44992845669)에서 확인할 수 있습니다.
구 리소스 삭제 후에도 HTTPS, DB/Redis/SMTP 연결, 로그인, 오늘의 질문 API를 검증했습니다.

## 운영 명령

Terraform 1.10 이상에서 저장소 루트 기준으로 실행합니다.
`afternote-pm` 프로필과 Git에서 제외된 운영 `terraform.tfvars`를 준비합니다.

```bash
aws sts get-caller-identity --profile afternote-pm
terraform -chdir=infra/terraform-pm init
terraform -chdir=infra/terraform-pm fmt -check
terraform -chdir=infra/terraform-pm validate
terraform -chdir=infra/terraform-pm plan
```

`init`은 PM 계정의 비공개 S3에서 기존 운영 state를 읽습니다.
새 PC에서는 로컬 state를 복사하지 않습니다. 운영 변수 파일은 별도로 안전하게 전달합니다.

## S3 원격 state

- 버킷: `afternote-terraform-state-079477842373-ap-northeast-2`
- state 키: `prod/terraform.tfstate`
- 잠금 키: `prod/terraform.tfstate.tflock` (`use_lockfile = true`)
- PM 계정만 허용하며, 공개 접근 차단·버킷 소유자 강제·AES256 암호화·버전 관리·HTTPS 강제를 적용합니다.
- state 버킷도 이 루트에서 관리하며 `prevent_destroy = true`로 실수에 의한 삭제를 막습니다.
- 2026-11-23 현재 PM state를 이전했습니다. 이전 계정의 폐기된 state는 원격 backend에 넣지 않았습니다.

운영자는 기존 인프라 권한 외에 state 버킷의 `s3:ListBucket`, state 객체의
`s3:GetObject`/`s3:PutObject`, 잠금 객체의 `s3:GetObject`/`s3:PutObject`/`s3:DeleteObject`
권한이 필요합니다. 앱의 업로드 전용 IAM 사용자는 state 버킷 권한을 갖지 않습니다.
동시에 실행된 Terraform 작업은 잠금으로 차단됩니다. 실행 중인 작업이 있다면
잠금 객체를 직접 지우거나 `force-unlock`으로 우회하지 않고 해당 작업이 끝나기를 기다립니다.

이미 운영 중인 환경에서는 `terraform init`만 실행합니다.
버킷을 다시 만들거나 `-migrate-state`/`-force-copy`로 오래된 로컬 state를 덮어쓰지 않습니다.
이전 전후 백업은 Git에서 제외된 `.state-migration-backups/20261123/`에 보관합니다.

완전한 재해 복구로 버킷부터 다시 만드는 경우에는 먼저 `backend.tf`를 제외한 임시 루트에서
버킷을 준비한 뒤 올바른 최신 state를 복원하고 backend를 연결해야 합니다.
일반적인 clone과 운영 작업에서는 이 부트스트랩 절차가 필요하지 않습니다.

## 구성과 배포

- VPC, 서브넷, EC2(`t3.small`), EIP, 비공개 MySQL 8.4 RDS(`db.t4g.micro`).
- 비공개 S3, CloudFront OAC, 업로드 버킷에만 접근하는 앱 전용 IAM 사용자.
- EC2 SSM 역할, CloudWatch 로그·알람·대시보드, SNS 알림.
- 한국시간 03:00 중지 / 12:00 시작 스케줄. 해당 시간 동안 서비스는 중단됩니다.
- RDS 삭제 방지와 최종 스냅샷을 활성화합니다.
- `deploy-key.pub`로 SSH 키페어를 관리합니다. 개인 키 `deploy-key`는 Git에서 제외합니다.
- EC2 부팅 시 `afternote-compose` 서비스가 `/home/ec2-user/deploy`의 Compose를 기동합니다.
- Amazon Linux의 기존 `curl-minimal`과 충돌하지 않도록 Docker와 curl을 따로 처리합니다.

GitHub Actions의 `EC2_HOST`, `EC2_USER`, `EC2_KEY`, `DEPLOY_PRODUCTION_ENV`가
이 서버를 대상으로 합니다. 앱 환경설정 원본은 Git에서 제외된
`deploy/production.env`이며, EC2에서는 `~/deploy/.env`로 사용합니다.
`APP_BASE_URL`은 `https://afternote.kro.kr`입니다.
DockerHub 이미지, 메일, Firebase 등 외부 서비스는 기존 설정을 재사용합니다.

```bash
terraform -chdir=infra/terraform-pm output elastic_ip
terraform -chdir=infra/terraform-pm output jdbc_url_hint
terraform -chdir=infra/terraform-pm output uploads_base_url
```

## 필수 초기 데이터

스키마는 앱의 JPA 설정으로 생성되지만 공통 질문은 자동 생성되지 않습니다.
2026-11-22 이전 시 `daily_question`의 질문 100개와 활성 상태를 복사했습니다.
사용자 정보, 질문 답변과 기존 업로드 파일은 이전하지 않았습니다.
새 DB를 다시 만들 때는 공통 질문을 복원하고 `/api/v1/daily-questions/today`가
로그인 후 200과 질문 내용을 반환하는지 확인해야 합니다.

배포 계약 테스트에는 일반 권한의 전용 계정이 필요합니다.
새 DB에서는 이 계정도 준비하고 GitHub의 `CONTRACT_TEST_EMAIL`과
`CONTRACT_TEST_PASSWORD`를 일치시켜야 합니다.

## 보관할 로컬 파일

`terraform.tfstate`와 백업, `terraform.tfvars`, `deploy-key`, 운영 env,
저장된 plan에는 인증정보가 포함될 수 있습니다. Git에서 제외한 상태로 안전하게 보관합니다.
잠금 파일 `.terraform.lock.hcl`과 공개 키 `deploy-key.pub`는 버전 관리합니다.

provider 잠금 파일을 갱신할 때는 Linux CI와 macOS의 체크섬을 함께 기록합니다.
CI는 `-lockfile=readonly`로 실행하므로 누락된 플랫폼 해시를 자동으로 보완하지 않습니다.

```bash
terraform -chdir=infra/terraform-pm providers lock -platform=linux_amd64 -platform=darwin_arm64
```

완전히 새 환경을 생성할 때만 `terraform.tfvars.example`을 복사해 값을 채우고,
새 SSH 개인 키와 공개 키를 준비합니다. 기존 운영 환경에서는 키나 원격 state를
덮어쓰지 않습니다. `ssh_ingress_cidr`에는 실제 SSH 배포 주체가 접근할 수 있는
범위가 필요하며 GitHub Actions의 SSH 배포도 이 규칙의 적용을 받습니다.
11 changes: 11 additions & 0 deletions infra/terraform-pm/backend.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
terraform {
backend "s3" {
bucket = "afternote-terraform-state-079477842373-ap-northeast-2"
key = "prod/terraform.tfstate"
region = "ap-northeast-2"
profile = "afternote-pm"
allowed_account_ids = ["079477842373"]
encrypt = true
use_lockfile = true
}
}
1 change: 1 addition & 0 deletions infra/terraform-pm/deploy-key.pub
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC5E/bJLe+gq+LJqQIitPa+2WWNNqIFZpVtLtxwxEav+ch9+RBV7mtfW8/KMF8p1PNKW6lyiSPJ5/Ia/MDNBLkVf4uvOe+Z2wHUY4QgG2TeLs+KS/d0EES09jH0wfrRu5sSbOUWd2HAEIGm8UfiwhVRy4rM3W2B0k9bh4il6HeHdivp/gbgk8PXtU2pGqKRii4nRf7HDjKHQ4q1NsbiNMfiaHxe7IkKSo7rH7hyRv8raCX42LZayCb8qzA2S7JldpjtDsKiNqGlIv06sP05ThHpKtZnjEt5A2rE4GoR973zpre/6MMvpaAkJRz+ZcQG2n9hkdjLYy6cqkjd3iAIllp8KmQ4zHaFBtb1dNw0TsnyoUO+YyJK0Ay31qBO8bZgK6nLR/rUoydDLKyJEo9hS6FwmrcTpLDSluNseLQ+KHB21AQSzH2E9o1azAprBel/ra9aV/PqLRrX7zGVh1Ju3tfvfo/Z3UP6V9vOxpIf/Rij2TKQR2WFkgJZ3Ho3BFhdgis= afternote-pm-deploy
42 changes: 42 additions & 0 deletions infra/terraform-pm/ec2.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
data "aws_ami" "al2023" {
most_recent = true
owners = ["amazon"]

filter {
name = "name"
values = ["al2023-ami-*-x86_64"]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}
}

resource "aws_instance" "app" {
ami = data.aws_ami.al2023.id
instance_type = var.ec2_instance_type
subnet_id = aws_subnet.public[0].id
vpc_security_group_ids = [aws_security_group.ec2.id]
key_name = aws_key_pair.deploy.key_name
iam_instance_profile = aws_iam_instance_profile.ec2_ssm.name
associate_public_ip_address = true
user_data = templatefile("${path.module}/templates/ec2_user_data.sh.tftpl", {
deploy_path = var.deploy_path
ec2_user = var.ec2_user
})

root_block_device {
volume_size = 30
volume_type = "gp3"
}

tags = {
Name = "${var.project_name}-app"
}

# most_recent AMI가 바뀌어도 운영 중인 인스턴스를 교체하지 않는다.
lifecycle {
ignore_changes = [ami]
}
}
23 changes: 23 additions & 0 deletions infra/terraform-pm/eip.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
resource "aws_eip" "app" {
count = var.existing_eip_allocation_id == "" ? 1 : 0
domain = "vpc"

tags = {
Name = "${var.project_name}-ec2-eip"
}
}

locals {
eip_allocation_id = var.existing_eip_allocation_id != "" ? var.existing_eip_allocation_id : aws_eip.app[0].id
ec2_instance_id = aws_instance.app.id
rds_instance_id = aws_db_instance.main.identifier
}

resource "aws_eip_association" "app" {
instance_id = aws_instance.app.id
allocation_id = local.eip_allocation_id
}

data "aws_eip" "associated" {
id = local.eip_allocation_id
}
Loading
Loading