diff --git a/.github/CI.md b/.github/CI.md index 7bd9769..2cc7a15 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -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 배포 흐름 | diff --git a/.github/workflows/terraform.yml b/.github/workflows/terraform.yml new file mode 100644 index 0000000..f0ddd94 --- /dev/null +++ b/.github/workflows/terraform.yml @@ -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 diff --git a/README.md b/README.md index 57825bd..11e99f0 100644 --- a/README.md +++ b/README.md @@ -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 ``` ### 실행 방법 diff --git a/infra/terraform-pm/.gitignore b/infra/terraform-pm/.gitignore new file mode 100644 index 0000000..9610d9e --- /dev/null +++ b/infra/terraform-pm/.gitignore @@ -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 diff --git a/infra/terraform-pm/.terraform.lock.hcl b/infra/terraform-pm/.terraform.lock.hcl new file mode 100644 index 0000000..00d462e --- /dev/null +++ b/infra/terraform-pm/.terraform.lock.hcl @@ -0,0 +1,48 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/archive" { + version = "2.8.0" + constraints = "~> 2.0" + hashes = [ + "h1:WB6H5ksIZiyq1lQlD/PWeh+tn4FLsbSjVnRW3+4xe2Y=", + "h1:jdmKm+xl6ZcQrijxapnZ94RVuz/G4vk7hsIa1N0VT5Q=", + "zh:0d14713fdc259fb377d0b899ad3c650a34194bd52194c863303ef22a65a580e2", + "zh:369b56040c7a8085d04e7e8ffac1e2b321a3170e502f788819bc34b868ec016f", + "zh:4d1a3b983ed6af5a52bfe12794674ae55cbadfa6021b37106ade68b433ad216a", + "zh:5c547549e26e083573c78a966ca68ce6d7df6bb8f3948f66a575f07da46b74ea", + "zh:6de093e62a975eb19a5e3017ce38e6e3cb639c17b79648d2000e0a8348f0e997", + "zh:7267936c2cdbc448efeb594d73e6b56a53d6a7ae14fe88cdd2a4133adc3302f0", + "zh:7482f023050ed426b4b45116e1761643bc33b1fd4ce4a6fab207ae2571f35940", + "zh:76bbd93b234e5a2927d98b511d86565700f549b570871a194c35f944b96cefb7", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:c6afc4bc1f002bac9c173007dd4da05fde788cd14c2916089f958c33fedb0dfa", + "zh:d3ba40bd806a3a08e9237dece679193c99afb2085de6b45d7f5d1f673cfcd368", + "zh:e1ad7ded53ecd6f0e5b473a3b44eae2b2e885653a56050ab583d387332be02e4", + "zh:e93e78575ce82be6084cc153c24ba8f385dc8d6880888ee66e918460c870953d", + ] +} + +provider "registry.terraform.io/hashicorp/aws" { + version = "5.100.0" + constraints = "~> 5.0" + hashes = [ + "h1:Ijt7pOlB7Tr7maGQIqtsLFbl7pSMIj06TVdkoSBcYOw=", + "h1:edXOJWE4ORX8Fm+dpVpICzMZJat4AX0VRCAy/xkcOc0=", + "zh:054b8dd49f0549c9a7cc27d159e45327b7b65cf404da5e5a20da154b90b8a644", + "zh:0b97bf8d5e03d15d83cc40b0530a1f84b459354939ba6f135a0086c20ebbe6b2", + "zh:1589a2266af699cbd5d80737a0fe02e54ec9cf2ca54e7e00ac51c7359056f274", + "zh:6330766f1d85f01ae6ea90d1b214b8b74cc8c1badc4696b165b36ddd4cc15f7b", + "zh:7c8c2e30d8e55291b86fcb64bdf6c25489d538688545eb48fd74ad622e5d3862", + "zh:99b1003bd9bd32ee323544da897148f46a527f622dc3971af63ea3e251596342", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:9f8b909d3ec50ade83c8062290378b1ec553edef6a447c56dadc01a99f4eaa93", + "zh:aaef921ff9aabaf8b1869a86d692ebd24fbd4e12c21205034bb679b9caf883a2", + "zh:ac882313207aba00dd5a76dbd572a0ddc818bb9cbf5c9d61b28fe30efaec951e", + "zh:bb64e8aff37becab373a1a0cc1080990785304141af42ed6aa3dd4913b000421", + "zh:dfe495f6621df5540d9c92ad40b8067376350b005c637ea6efac5dc15028add4", + "zh:f0ddf0eaf052766cfe09dea8200a946519f653c384ab4336e2a4a64fdd6310e9", + "zh:f1b7e684f4c7ae1eed272b6de7d2049bb87a0275cb04dbb7cda6636f600699c9", + "zh:ff461571e3f233699bf690db319dfe46aec75e58726636a0d97dd9ac6e32fb70", + ] +} diff --git a/infra/terraform-pm/README.md b/infra/terraform-pm/README.md new file mode 100644 index 0000000..8b75678 --- /dev/null +++ b/infra/terraform-pm/README.md @@ -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 배포도 이 규칙의 적용을 받습니다. diff --git a/infra/terraform-pm/backend.tf b/infra/terraform-pm/backend.tf new file mode 100644 index 0000000..5a74621 --- /dev/null +++ b/infra/terraform-pm/backend.tf @@ -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 + } +} diff --git a/infra/terraform-pm/deploy-key.pub b/infra/terraform-pm/deploy-key.pub new file mode 100644 index 0000000..df8fb78 --- /dev/null +++ b/infra/terraform-pm/deploy-key.pub @@ -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 diff --git a/infra/terraform-pm/ec2.tf b/infra/terraform-pm/ec2.tf new file mode 100644 index 0000000..58ded9d --- /dev/null +++ b/infra/terraform-pm/ec2.tf @@ -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] + } +} diff --git a/infra/terraform-pm/eip.tf b/infra/terraform-pm/eip.tf new file mode 100644 index 0000000..3eb9d16 --- /dev/null +++ b/infra/terraform-pm/eip.tf @@ -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 +} diff --git a/infra/terraform-pm/iam.tf b/infra/terraform-pm/iam.tf new file mode 100644 index 0000000..679b3a9 --- /dev/null +++ b/infra/terraform-pm/iam.tf @@ -0,0 +1,139 @@ +resource "aws_iam_role" "lambda_scheduler" { + name = "${var.project_name}-scheduler-lambda" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + }] + }) +} + +resource "aws_iam_role_policy" "lambda_scheduler" { + name = "${var.project_name}-scheduler-lambda-policy" + role = aws_iam_role.lambda_scheduler.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:StartInstances", + "ec2:StopInstances", + "ec2:DescribeInstances", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "rds:StartDBInstance", + "rds:StopDBInstance", + "rds:DescribeDBInstances", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = [ + "ssm:SendCommand", + "ssm:GetCommandInvocation", + "ssm:DescribeInstanceInformation", + ] + Resource = "*" + }, + { + Effect = "Allow" + Action = ["sns:Publish"] + Resource = aws_sns_topic.scheduler_alerts.arn + }, + { + Effect = "Allow" + Action = [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents", + ] + Resource = "arn:aws:logs:${var.aws_region}:*:*" + }, + ] + }) +} + +resource "aws_iam_role" "scheduler_invoke" { + name = "${var.project_name}-eventbridge-scheduler" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { Service = "scheduler.amazonaws.com" } + }] + }) +} + +resource "aws_iam_role_policy" "scheduler_invoke" { + name = "${var.project_name}-eventbridge-scheduler-policy" + role = aws_iam_role.scheduler_invoke.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["lambda:InvokeFunction"] + Resource = [aws_lambda_function.stop_env.arn, aws_lambda_function.start_env.arn] + }] + }) +} + +# EC2 SSM — Start Lambda may still Run Command compose; boot also uses systemd +resource "aws_iam_role" "ec2_ssm" { + name = "${var.project_name}-ec2-ssm" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { Service = "ec2.amazonaws.com" } + }] + }) +} + +resource "aws_iam_role_policy_attachment" "ec2_ssm" { + role = aws_iam_role.ec2_ssm.name + policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" +} + +# Docker awslogs driver → CloudWatch Logs +resource "aws_iam_role_policy" "ec2_cloudwatch_logs" { + name = "${var.project_name}-ec2-cloudwatch-logs" + role = aws_iam_role.ec2_ssm.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:DescribeLogStreams", + "logs:PutLogEvents", + ] + Resource = [ + "${aws_cloudwatch_log_group.app.arn}", + "${aws_cloudwatch_log_group.app.arn}:*", + ] + }, + ] + }) +} + +resource "aws_iam_instance_profile" "ec2_ssm" { + name = "${var.project_name}-ec2-ssm" + role = aws_iam_role.ec2_ssm.name +} diff --git a/infra/terraform-pm/lambda.tf b/infra/terraform-pm/lambda.tf new file mode 100644 index 0000000..47181c3 --- /dev/null +++ b/infra/terraform-pm/lambda.tf @@ -0,0 +1,82 @@ +data "archive_file" "stop_lambda" { + type = "zip" + source_file = "${path.module}/lambda_stop.py" + output_path = "${path.module}/.build/stop_lambda.zip" +} + +data "archive_file" "start_lambda" { + type = "zip" + source_file = "${path.module}/lambda_start.py" + output_path = "${path.module}/.build/start_lambda.zip" +} + +resource "aws_cloudwatch_log_group" "stop_lambda" { + name = "/aws/lambda/${var.project_name}-stop-env" + retention_in_days = 14 +} + +resource "aws_cloudwatch_log_group" "start_lambda" { + name = "/aws/lambda/${var.project_name}-start-env" + retention_in_days = 14 +} + +resource "aws_lambda_function" "stop_env" { + function_name = "${var.project_name}-stop-env" + role = aws_iam_role.lambda_scheduler.arn + handler = "lambda_stop.handler" + runtime = "python3.12" + timeout = 120 + memory_size = 128 + + filename = data.archive_file.stop_lambda.output_path + source_code_hash = data.archive_file.stop_lambda.output_base64sha256 + + environment { + variables = { + EC2_INSTANCE_ID = local.ec2_instance_id + RDS_INSTANCE_ID = local.rds_instance_id + } + } + + depends_on = [aws_cloudwatch_log_group.stop_lambda] +} + +resource "aws_lambda_function" "start_env" { + function_name = "${var.project_name}-start-env" + role = aws_iam_role.lambda_scheduler.arn + handler = "lambda_start.handler" + runtime = "python3.12" + timeout = 600 + memory_size = 128 + + filename = data.archive_file.start_lambda.output_path + source_code_hash = data.archive_file.start_lambda.output_base64sha256 + + environment { + variables = { + EC2_INSTANCE_ID = local.ec2_instance_id + RDS_INSTANCE_ID = local.rds_instance_id + DEPLOY_PATH = var.deploy_path + EC2_USER = var.ec2_user + SNS_TOPIC_ARN = aws_sns_topic.scheduler_alerts.arn + } + } + + depends_on = [aws_cloudwatch_log_group.start_lambda] +} + +resource "aws_lambda_permission" "scheduler_stop" { + statement_id = "AllowEventBridgeSchedulerStop" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.stop_env.function_name + principal = "scheduler.amazonaws.com" + source_arn = aws_scheduler_schedule.stop_env.arn +} + +resource "aws_lambda_permission" "scheduler_start" { + statement_id = "AllowEventBridgeSchedulerStart" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.start_env.function_name + principal = "scheduler.amazonaws.com" + source_arn = aws_scheduler_schedule.start_env.arn +} diff --git a/infra/terraform-pm/lambda_start.py b/infra/terraform-pm/lambda_start.py new file mode 100644 index 0000000..014abae --- /dev/null +++ b/infra/terraform-pm/lambda_start.py @@ -0,0 +1,144 @@ +import os +import shlex +import time + +import boto3 +from botocore.exceptions import ClientError + +ec2 = boto3.client("ec2") +rds = boto3.client("rds") +ssm = boto3.client("ssm") + +EC2_INSTANCE_ID = os.environ["EC2_INSTANCE_ID"] +RDS_INSTANCE_ID = os.environ["RDS_INSTANCE_ID"] +DEPLOY_PATH = os.environ["DEPLOY_PATH"] +EC2_USER = os.environ.get("EC2_USER", "ec2-user") +SNS_TOPIC_ARN = os.environ.get("SNS_TOPIC_ARN", "") + +# deploy.yml 과 동일하게 ec2-user 로 compose 실행 (SSM 기본 root 는 compose plugin 없음) +DOCKER_START_SCRIPT = ( + f"set -e; cd {DEPLOY_PATH}; " + "if docker compose version >/dev/null 2>&1; then " + "docker compose up -d --remove-orphans && docker compose ps; " + "elif command -v docker-compose >/dev/null 2>&1; then " + "docker-compose up -d --remove-orphans && docker-compose ps; " + "else echo 'docker compose not found' >&2; exit 1; fi" +) + + +def notify_failure(message: str) -> None: + if not SNS_TOPIC_ARN: + return + sns = boto3.client("sns") + sns.publish( + TopicArn=SNS_TOPIC_ARN, + Subject="[Afternote] Start environment failed", + Message=message, + ) + + +def wait_rds_available(db_id: str, max_wait: int = 600) -> None: + for _ in range(max_wait // 15): + response = rds.describe_db_instances(DBInstanceIdentifier=db_id) + status = response["DBInstances"][0]["DBInstanceStatus"] + print(f"RDS {db_id} status: {status}") + if status == "available": + return + if status in ("failed", "incompatible-restore", "incompatible-network"): + raise RuntimeError(f"RDS {db_id} is in bad state: {status}") + time.sleep(15) + raise TimeoutError(f"RDS {db_id} not available within {max_wait}s") + + +def wait_ssm_online(instance_id: str, max_wait: int = 180) -> None: + """EC2 cold start 후 SSM Agent가 Online 될 때까지 대기.""" + for attempt in range(max_wait // 10): + response = ssm.describe_instance_information( + Filters=[{"Key": "InstanceIds", "Values": [instance_id]}] + ) + instances = response.get("InstanceInformationList", []) + if instances and instances[0].get("PingStatus") == "Online": + print(f"SSM Online for {instance_id}") + return + print(f"Waiting for SSM Online (attempt {attempt + 1})...") + time.sleep(10) + raise RuntimeError( + f"EC2 {instance_id} is not SSM Online after {max_wait}s. " + "Check Systems Manager Fleet Manager and IAM AmazonSSMManagedInstanceCore." + ) + + +def wait_ssm_command(command_id: str, instance_id: str, max_wait: int = 300) -> None: + for attempt in range(max_wait // 5): + try: + invocation = ssm.get_command_invocation( + CommandId=command_id, + InstanceId=instance_id, + ) + except ClientError as exc: + code = exc.response.get("Error", {}).get("Code", "") + if code == "InvocationDoesNotExist": + print(f"SSM invocation not registered yet (attempt {attempt + 1})") + time.sleep(5) + continue + raise + + status = invocation["Status"] + print(f"SSM command status: {status}") + if status == "Success": + print(invocation.get("StandardOutputContent", "")) + return + if status in ("Failed", "Cancelled", "TimedOut"): + stderr = invocation.get("StandardErrorContent", "") + stdout = invocation.get("StandardOutputContent", "") + raise RuntimeError(f"SSM command {status}. stdout={stdout} stderr={stderr}") + time.sleep(5) + + raise TimeoutError(f"SSM command {command_id} did not finish within {max_wait}s") + + +def handler(event, context): + try: + print(f"Starting RDS {RDS_INSTANCE_ID}") + try: + rds.start_db_instance(DBInstanceIdentifier=RDS_INSTANCE_ID) + except rds.exceptions.InvalidDBInstanceStateFault as exc: + print(f"RDS start skipped: {exc}") + + wait_rds_available(RDS_INSTANCE_ID) + + print(f"Starting EC2 {EC2_INSTANCE_ID}") + ec2.start_instances(InstanceIds=[EC2_INSTANCE_ID]) + waiter = ec2.get_waiter("instance_running") + waiter.wait( + InstanceIds=[EC2_INSTANCE_ID], + WaiterConfig={"Delay": 15, "MaxAttempts": 40}, + ) + + wait_ssm_online(EC2_INSTANCE_ID) + + print("Starting docker compose via SSM") + command = ssm.send_command( + InstanceIds=[EC2_INSTANCE_ID], + DocumentName="AWS-RunShellScript", + Parameters={ + "commands": [ + "sudo systemctl start docker 2>/dev/null || true", + f"sudo -u {EC2_USER} bash -lc {shlex.quote(DOCKER_START_SCRIPT)}", + ] + }, + TimeoutSeconds=300, + ) + command_id = command["Command"]["CommandId"] + time.sleep(3) + wait_ssm_command(command_id, EC2_INSTANCE_ID) + + return { + "status": "started", + "ec2_instance_id": EC2_INSTANCE_ID, + "rds_instance_id": RDS_INSTANCE_ID, + "ssm_command_id": command_id, + } + except Exception as exc: + notify_failure(str(exc)) + raise diff --git a/infra/terraform-pm/lambda_stop.py b/infra/terraform-pm/lambda_stop.py new file mode 100644 index 0000000..de806d1 --- /dev/null +++ b/infra/terraform-pm/lambda_stop.py @@ -0,0 +1,23 @@ +import json +import os + +import boto3 + +ec2 = boto3.client("ec2") +rds = boto3.client("rds") + + +def handler(event, context): + ec2_id = os.environ["EC2_INSTANCE_ID"] + rds_id = os.environ["RDS_INSTANCE_ID"] + + print(f"Stopping EC2 {ec2_id}") + ec2.stop_instances(InstanceIds=[ec2_id]) + + print(f"Stopping RDS {rds_id}") + try: + rds.stop_db_instance(DBInstanceIdentifier=rds_id) + except rds.exceptions.InvalidDBInstanceStateFault as exc: + print(f"RDS stop skipped (already stopped/stopping): {exc}") + + return {"status": "stopped", "ec2_instance_id": ec2_id, "rds_instance_id": rds_id} diff --git a/infra/terraform-pm/main.tf b/infra/terraform-pm/main.tf new file mode 100644 index 0000000..3e4397f --- /dev/null +++ b/infra/terraform-pm/main.tf @@ -0,0 +1,15 @@ +# PM account stack. Keep its local state separate from ../terraform. +# Run Terraform in this directory using the afternote-pm AWS profile. +provider "aws" { + region = var.aws_region + profile = "afternote-pm" + allowed_account_ids = ["079477842373"] + + default_tags { + tags = { + Project = var.project_name + ManagedBy = "terraform" + Environment = var.environment + } + } +} diff --git a/infra/terraform-pm/monitoring.tf b/infra/terraform-pm/monitoring.tf new file mode 100644 index 0000000..d51f6d9 --- /dev/null +++ b/infra/terraform-pm/monitoring.tf @@ -0,0 +1,294 @@ +# --- App logs (docker awslogs) --- + +resource "aws_cloudwatch_log_group" "app" { + name = "/${var.project_name}/app" + retention_in_days = 14 + + tags = { + Name = "${var.project_name}-app-logs" + } +} + +# Infra alerts (EC2 / RDS / scheduler Lambda). Same SNS topic for all. +# Off-hours EC2/RDS stop: missing metrics must NOT alarm → treat_missing_data = notBreaching. + +resource "aws_sns_topic" "scheduler_alerts" { + name = "${var.project_name}-scheduler-alerts" +} + +resource "aws_sns_topic_subscription" "scheduler_alerts_email" { + topic_arn = aws_sns_topic.scheduler_alerts.arn + protocol = "email" + endpoint = var.alert_email +} + +# --- Lambda (existing) --- + +resource "aws_cloudwatch_metric_alarm" "stop_lambda_errors" { + alarm_name = "${var.project_name}-stop-lambda-errors" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 1 + metric_name = "Errors" + namespace = "AWS/Lambda" + period = 300 + statistic = "Sum" + threshold = 0 + treat_missing_data = "notBreaching" + alarm_description = "Stop Lambda failed" + + dimensions = { + FunctionName = aws_lambda_function.stop_env.function_name + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +resource "aws_cloudwatch_metric_alarm" "start_lambda_errors" { + alarm_name = "${var.project_name}-start-lambda-errors" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 1 + metric_name = "Errors" + namespace = "AWS/Lambda" + period = 300 + statistic = "Sum" + threshold = 0 + treat_missing_data = "notBreaching" + alarm_description = "Start Lambda failed (environment may not be running)" + + dimensions = { + FunctionName = aws_lambda_function.start_env.function_name + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +# --- EC2 --- + +resource "aws_cloudwatch_metric_alarm" "ec2_status_check" { + alarm_name = "${var.project_name}-ec2-status-check" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 2 + metric_name = "StatusCheckFailed" + namespace = "AWS/EC2" + period = 60 + statistic = "Maximum" + threshold = 0 + treat_missing_data = "notBreaching" + alarm_description = "EC2 instance status check failed (host/instance unhealthy). Silent while stopped off-hours." + + dimensions = { + InstanceId = aws_instance.app.id + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +resource "aws_cloudwatch_metric_alarm" "ec2_cpu_high" { + alarm_name = "${var.project_name}-ec2-cpu-high" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 2 + metric_name = "CPUUtilization" + namespace = "AWS/EC2" + period = 300 + statistic = "Average" + threshold = 80 + treat_missing_data = "notBreaching" + alarm_description = "EC2 CPU > 80% for 10 minutes. Silent while stopped off-hours." + + dimensions = { + InstanceId = aws_instance.app.id + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +# --- RDS --- + +resource "aws_cloudwatch_metric_alarm" "rds_free_storage_low" { + alarm_name = "${var.project_name}-rds-free-storage-low" + comparison_operator = "LessThanThreshold" + evaluation_periods = 1 + metric_name = "FreeStorageSpace" + namespace = "AWS/RDS" + period = 300 + statistic = "Average" + # ~2 GiB + threshold = 2147483648 + treat_missing_data = "notBreaching" + alarm_description = "RDS free storage < 2 GiB. Silent while stopped off-hours." + + dimensions = { + DBInstanceIdentifier = aws_db_instance.main.identifier + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +resource "aws_cloudwatch_metric_alarm" "rds_connections_high" { + alarm_name = "${var.project_name}-rds-connections-high" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 2 + metric_name = "DatabaseConnections" + namespace = "AWS/RDS" + period = 300 + statistic = "Average" + threshold = 40 + treat_missing_data = "notBreaching" + alarm_description = "RDS connections > 40 for 10 minutes (pool leak / traffic spike). Silent while stopped off-hours." + + dimensions = { + DBInstanceIdentifier = aws_db_instance.main.identifier + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +resource "aws_cloudwatch_metric_alarm" "rds_cpu_high" { + alarm_name = "${var.project_name}-rds-cpu-high" + comparison_operator = "GreaterThanThreshold" + evaluation_periods = 2 + metric_name = "CPUUtilization" + namespace = "AWS/RDS" + period = 300 + statistic = "Average" + threshold = 80 + treat_missing_data = "notBreaching" + alarm_description = "RDS CPU > 80% for 10 minutes. Silent while stopped off-hours." + + dimensions = { + DBInstanceIdentifier = aws_db_instance.main.identifier + } + + alarm_actions = [aws_sns_topic.scheduler_alerts.arn] +} + +# --- Dashboard --- + +resource "aws_cloudwatch_dashboard" "scheduler" { + dashboard_name = "${var.project_name}-ops" + + dashboard_body = jsonencode({ + widgets = [ + { + type = "metric" + x = 0 + y = 0 + width = 12 + height = 6 + properties = { + title = "EC2 CPU %" + region = var.aws_region + metrics = [ + ["AWS/EC2", "CPUUtilization", "InstanceId", aws_instance.app.id, { stat = "Average", label = "CPU" }], + ] + period = 300 + view = "timeSeries" + yAxis = { + left = { min = 0, max = 100 } + } + } + }, + { + type = "metric" + x = 12 + y = 0 + width = 12 + height = 6 + properties = { + title = "EC2 StatusCheckFailed" + region = var.aws_region + metrics = [ + ["AWS/EC2", "StatusCheckFailed", "InstanceId", aws_instance.app.id, { stat = "Maximum", label = "Failed" }], + ] + period = 60 + view = "timeSeries" + } + }, + { + type = "metric" + x = 0 + y = 6 + width = 8 + height = 6 + properties = { + title = "RDS CPU %" + region = var.aws_region + metrics = [ + ["AWS/RDS", "CPUUtilization", "DBInstanceIdentifier", aws_db_instance.main.identifier, { stat = "Average" }], + ] + period = 300 + view = "timeSeries" + yAxis = { + left = { min = 0, max = 100 } + } + } + }, + { + type = "metric" + x = 8 + y = 6 + width = 8 + height = 6 + properties = { + title = "RDS FreeStorageSpace" + region = var.aws_region + metrics = [ + ["AWS/RDS", "FreeStorageSpace", "DBInstanceIdentifier", aws_db_instance.main.identifier, { stat = "Average" }], + ] + period = 300 + view = "timeSeries" + } + }, + { + type = "metric" + x = 16 + y = 6 + width = 8 + height = 6 + properties = { + title = "RDS DatabaseConnections" + region = var.aws_region + metrics = [ + ["AWS/RDS", "DatabaseConnections", "DBInstanceIdentifier", aws_db_instance.main.identifier, { stat = "Average" }], + ] + period = 300 + view = "timeSeries" + } + }, + { + type = "metric" + x = 0 + y = 12 + width = 12 + height = 6 + properties = { + title = "Lambda Invocations" + region = var.aws_region + metrics = [ + ["AWS/Lambda", "Invocations", "FunctionName", aws_lambda_function.stop_env.function_name, { stat = "Sum", label = "Stop" }], + [".", "Invocations", ".", aws_lambda_function.start_env.function_name, { stat = "Sum", label = "Start" }], + ] + period = 300 + view = "timeSeries" + } + }, + { + type = "metric" + x = 12 + y = 12 + width = 12 + height = 6 + properties = { + title = "Lambda Errors" + region = var.aws_region + metrics = [ + ["AWS/Lambda", "Errors", "FunctionName", aws_lambda_function.stop_env.function_name, { stat = "Sum", label = "Stop" }], + [".", "Errors", ".", aws_lambda_function.start_env.function_name, { stat = "Sum", label = "Start" }], + ] + period = 300 + view = "timeSeries" + } + }, + ] + }) +} diff --git a/infra/terraform-pm/network.tf b/infra/terraform-pm/network.tf new file mode 100644 index 0000000..d81ecea --- /dev/null +++ b/infra/terraform-pm/network.tf @@ -0,0 +1,54 @@ +data "aws_availability_zones" "available" { + state = "available" +} + +resource "aws_vpc" "main" { + cidr_block = var.vpc_cidr + enable_dns_hostnames = true + enable_dns_support = true + + tags = { + Name = "${var.project_name}-vpc" + } +} + +resource "aws_internet_gateway" "main" { + vpc_id = aws_vpc.main.id + + tags = { + Name = "${var.project_name}-igw" + } +} + +resource "aws_subnet" "public" { + count = 2 + + vpc_id = aws_vpc.main.id + cidr_block = var.public_subnet_cidrs[count.index] + availability_zone = data.aws_availability_zones.available.names[count.index] + map_public_ip_on_launch = true + + tags = { + Name = "${var.project_name}-public-${count.index + 1}" + } +} + +resource "aws_route_table" "public" { + vpc_id = aws_vpc.main.id + + route { + cidr_block = "0.0.0.0/0" + gateway_id = aws_internet_gateway.main.id + } + + tags = { + Name = "${var.project_name}-public-rt" + } +} + +resource "aws_route_table_association" "public" { + count = 2 + + subnet_id = aws_subnet.public[count.index].id + route_table_id = aws_route_table.public.id +} diff --git a/infra/terraform-pm/outputs.tf b/infra/terraform-pm/outputs.tf new file mode 100644 index 0000000..22d2dee --- /dev/null +++ b/infra/terraform-pm/outputs.tf @@ -0,0 +1,83 @@ +output "elastic_ip" { + description = "Fixed public IP — set domain A record and GitHub secret EC2_HOST" + value = data.aws_eip.associated.public_ip +} + +output "elastic_ip_allocation_id" { + description = "Elastic IP allocation ID" + value = local.eip_allocation_id +} + +output "ec2_instance_id" { + value = aws_instance.app.id +} + +output "rds_endpoint" { + description = "RDS hostname:port for DB_URL" + value = aws_db_instance.main.endpoint +} + +output "rds_address" { + value = aws_db_instance.main.address +} + +output "db_name" { + value = aws_db_instance.main.db_name +} + +output "db_username" { + value = aws_db_instance.main.username +} + +output "jdbc_url_hint" { + description = "Paste into .env.production as DB_URL (password from tfvars)" + value = "jdbc:mysql://${aws_db_instance.main.address}:3306/${aws_db_instance.main.db_name}?serverTimezone=Asia/Seoul&characterEncoding=UTF-8" +} + +output "stop_lambda_function_name" { + value = aws_lambda_function.stop_env.function_name +} + +output "start_lambda_function_name" { + value = aws_lambda_function.start_env.function_name +} + +output "stop_schedule" { + value = "${var.stop_schedule} (${var.schedule_timezone})" +} + +output "start_schedule" { + value = "${var.start_schedule} (${var.schedule_timezone})" +} + +output "cloudwatch_dashboard_name" { + description = "CloudWatch dashboard (EC2 + RDS + scheduler Lambda)" + value = aws_cloudwatch_dashboard.scheduler.dashboard_name +} + +output "cloudwatch_dashboard_url" { + description = "Open ops dashboard in console" + value = "https://${var.aws_region}.console.aws.amazon.com/cloudwatch/home?region=${var.aws_region}#dashboards:name=${aws_cloudwatch_dashboard.scheduler.dashboard_name}" +} + +output "app_log_group_name" { + description = "Docker awslogs group for afternote-server" + value = aws_cloudwatch_log_group.app.name +} + +output "app_log_group_url" { + description = "Open app logs in CloudWatch" + value = "https://${var.aws_region}.console.aws.amazon.com/cloudwatch/home?region=${var.aws_region}#logsV2:log-groups/log-group/${urlencode(aws_cloudwatch_log_group.app.name)}" +} + +output "sns_topic_arn" { + value = aws_sns_topic.scheduler_alerts.arn +} + +output "manual_test_commands" { + description = "Run after apply to verify stop/start without waiting for schedule" + value = <<-EOT + aws --profile afternote-pm --region ${var.aws_region} lambda invoke --function-name ${aws_lambda_function.stop_env.function_name} /tmp/afternote-stop.json + aws --profile afternote-pm --region ${var.aws_region} lambda invoke --function-name ${aws_lambda_function.start_env.function_name} /tmp/afternote-start.json + EOT +} diff --git a/infra/terraform-pm/rds.tf b/infra/terraform-pm/rds.tf new file mode 100644 index 0000000..8c3e653 --- /dev/null +++ b/infra/terraform-pm/rds.tf @@ -0,0 +1,39 @@ +resource "aws_db_subnet_group" "main" { + name = "${var.project_name}-db" + subnet_ids = aws_subnet.public[*].id + + tags = { + Name = "${var.project_name}-db-subnet" + } +} + +resource "aws_db_instance" "main" { + identifier = "${var.project_name}-${var.environment}" + + engine = "mysql" + engine_version = "8.4" + allow_major_version_upgrade = true + instance_class = var.db_instance_class + allocated_storage = var.db_allocated_storage + max_allocated_storage = 100 + storage_type = "gp3" + + db_name = var.db_name + username = var.db_username + password = var.db_password + + db_subnet_group_name = aws_db_subnet_group.main.name + vpc_security_group_ids = [aws_security_group.rds.id] + publicly_accessible = false + multi_az = false + + backup_retention_period = 1 + skip_final_snapshot = false + final_snapshot_identifier = "afternote-prod-final" + deletion_protection = true + apply_immediately = true + + tags = { + Name = "${var.project_name}-rds" + } +} diff --git a/infra/terraform-pm/scheduler.tf b/infra/terraform-pm/scheduler.tf new file mode 100644 index 0000000..457e717 --- /dev/null +++ b/infra/terraform-pm/scheduler.tf @@ -0,0 +1,43 @@ +resource "aws_scheduler_schedule" "stop_env" { + name = "${var.project_name}-stop-env" + group_name = "default" + + schedule_expression = var.stop_schedule + schedule_expression_timezone = var.schedule_timezone + state = "ENABLED" + + flexible_time_window { + mode = "OFF" + } + + target { + arn = aws_lambda_function.stop_env.arn + role_arn = aws_iam_role.scheduler_invoke.arn + + retry_policy { + maximum_retry_attempts = 2 + } + } +} + +resource "aws_scheduler_schedule" "start_env" { + name = "${var.project_name}-start-env" + group_name = "default" + + schedule_expression = var.start_schedule + schedule_expression_timezone = var.schedule_timezone + state = "ENABLED" + + flexible_time_window { + mode = "OFF" + } + + target { + arn = aws_lambda_function.start_env.arn + role_arn = aws_iam_role.scheduler_invoke.arn + + retry_policy { + maximum_retry_attempts = 2 + } + } +} diff --git a/infra/terraform-pm/security.tf b/infra/terraform-pm/security.tf new file mode 100644 index 0000000..0a1d25f --- /dev/null +++ b/infra/terraform-pm/security.tf @@ -0,0 +1,65 @@ +resource "aws_security_group" "ec2" { + name = "${var.project_name}-ec2" + description = "AfterNote app EC2 (SSH + HTTP/HTTPS)" + vpc_id = aws_vpc.main.id + + ingress { + description = "SSH" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = [var.ssh_ingress_cidr] + } + + ingress { + description = "HTTP" + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + ingress { + description = "HTTPS" + from_port = 443 + to_port = 443 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "${var.project_name}-ec2-sg" + } +} + +resource "aws_security_group" "rds" { + name = "${var.project_name}-rds" + description = "AfterNote RDS MySQL - EC2 only" + vpc_id = aws_vpc.main.id + + ingress { + description = "MySQL from EC2" + from_port = 3306 + to_port = 3306 + protocol = "tcp" + security_groups = [aws_security_group.ec2.id] + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "${var.project_name}-rds-sg" + } +} diff --git a/infra/terraform-pm/state.tf b/infra/terraform-pm/state.tf new file mode 100644 index 0000000..bf77e83 --- /dev/null +++ b/infra/terraform-pm/state.tf @@ -0,0 +1,63 @@ +# Kept in this stack so the state store is versioned with the infrastructure. +# prevent_destroy also blocks a whole-stack destroy until retirement is explicit. +resource "aws_s3_bucket" "terraform_state" { + bucket = "afternote-terraform-state-079477842373-ap-northeast-2" + + lifecycle { + prevent_destroy = true + } +} + +resource "aws_s3_bucket_public_access_block" "terraform_state" { + bucket = aws_s3_bucket.terraform_state.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "terraform_state" { + bucket = aws_s3_bucket.terraform_state.id + + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +resource "aws_s3_bucket_versioning" "terraform_state" { + bucket = aws_s3_bucket.terraform_state.id + + versioning_configuration { + status = "Enabled" + } +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" { + bucket = aws_s3_bucket.terraform_state.id + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_bucket_policy" "terraform_state" { + bucket = aws_s3_bucket.terraform_state.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "DenyInsecureTransport" + Effect = "Deny" + Principal = "*" + Action = "s3:*" + Resource = [ + aws_s3_bucket.terraform_state.arn, + "${aws_s3_bucket.terraform_state.arn}/*", + ] + Condition = { + Bool = { "aws:SecureTransport" = "false" } + } + }] + }) +} diff --git a/infra/terraform-pm/storage.tf b/infra/terraform-pm/storage.tf new file mode 100644 index 0000000..ae3ed4c --- /dev/null +++ b/infra/terraform-pm/storage.tf @@ -0,0 +1,104 @@ +resource "aws_s3_bucket" "uploads" { + bucket = "afternote-storage-079477842373-ap-northeast-2" +} + +resource "aws_s3_bucket_public_access_block" "uploads" { + bucket = aws_s3_bucket.uploads.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "uploads" { + bucket = aws_s3_bucket.uploads.id + rule { object_ownership = "BucketOwnerEnforced" } +} + +resource "aws_cloudfront_origin_access_control" "uploads" { + name = "afternote-uploads" + origin_access_control_origin_type = "s3" + signing_behavior = "always" + signing_protocol = "sigv4" +} + +resource "aws_cloudfront_distribution" "uploads" { + enabled = true + is_ipv6_enabled = true + price_class = "PriceClass_200" + origin { + domain_name = aws_s3_bucket.uploads.bucket_regional_domain_name + origin_id = "uploads" + origin_access_control_id = aws_cloudfront_origin_access_control.uploads.id + } + default_cache_behavior { + target_origin_id = "uploads" + viewer_protocol_policy = "redirect-to-https" + allowed_methods = ["GET", "HEAD"] + cached_methods = ["GET", "HEAD"] + compress = true + min_ttl = 0 + default_ttl = 86400 + max_ttl = 31536000 + forwarded_values { + query_string = false + cookies { forward = "none" } + } + } + restrictions { + geo_restriction { restriction_type = "none" } + } + viewer_certificate { cloudfront_default_certificate = true } +} + +resource "aws_s3_bucket_policy" "uploads" { + bucket = aws_s3_bucket.uploads.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Principal = { Service = "cloudfront.amazonaws.com" } + Action = "s3:GetObject" + Resource = "${aws_s3_bucket.uploads.arn}/*" + Condition = { StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.uploads.arn } } + }] + }) +} + +# The current application uses static credentials; keep deployment credentials +# separate from the Terraform operator and limit access to this bucket. +resource "aws_iam_user" "uploads" { + name = "afternote-app-uploads" +} + +resource "aws_iam_user_policy" "uploads" { + name = "afternote-app-uploads" + user = aws_iam_user.uploads.name + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { Effect = "Allow", Action = ["s3:ListBucket"], Resource = aws_s3_bucket.uploads.arn }, + { Effect = "Allow", Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], Resource = "${aws_s3_bucket.uploads.arn}/*" } + ] + }) +} + +resource "aws_iam_access_key" "uploads" { + user = aws_iam_user.uploads.name +} + +resource "aws_key_pair" "deploy" { + key_name = var.ec2_key_name + public_key = file("${path.module}/deploy-key.pub") +} + +output "uploads_bucket" { value = aws_s3_bucket.uploads.id } +output "uploads_base_url" { value = "https://${aws_cloudfront_distribution.uploads.domain_name}" } +output "uploads_access_key" { + value = aws_iam_access_key.uploads.id + sensitive = true +} +output "uploads_secret_key" { + value = aws_iam_access_key.uploads.secret + sensitive = true +} diff --git a/infra/terraform-pm/templates/ec2_user_data.sh.tftpl b/infra/terraform-pm/templates/ec2_user_data.sh.tftpl new file mode 100644 index 0000000..f9700a0 --- /dev/null +++ b/infra/terraform-pm/templates/ec2_user_data.sh.tftpl @@ -0,0 +1,59 @@ +#!/bin/bash +set -euxo pipefail + +dnf update -y +dnf install -y docker +command -v curl >/dev/null || dnf install -y curl-minimal +systemctl enable --now docker +usermod -aG docker ${ec2_user} + +# docker compose v2 plugin (AL2023 docker package often omits it) +mkdir -p /usr/libexec/docker/cli-plugins +curl -fsSL "https://github.com/docker/compose/releases/download/v2.29.7/docker-compose-linux-x86_64" \ + -o /usr/libexec/docker/cli-plugins/docker-compose +chmod +x /usr/libexec/docker/cli-plugins/docker-compose +docker compose version + +mkdir -p ${deploy_path} +chown ${ec2_user}:${ec2_user} ${deploy_path} + +cat >/usr/local/bin/afternote-compose-boot.sh <<'SCRIPT' +#!/bin/bash +set -euo pipefail +DEPLOY_PATH='${deploy_path}' +if [ ! -f "$DEPLOY_PATH/docker-compose.yml" ]; then + echo "compose not present yet at $DEPLOY_PATH" + exit 0 +fi +cd "$DEPLOY_PATH" +for i in $(seq 1 30); do + docker info >/dev/null 2>&1 && break + sleep 2 +done +if [ -f .env.production ]; then + docker compose --env-file .env.production up -d --remove-orphans +else + docker compose up -d --remove-orphans +fi +SCRIPT +chmod +x /usr/local/bin/afternote-compose-boot.sh + +cat >/etc/systemd/system/afternote-compose.service < 이전 계정(`312871631529`)의 레거시 구성입니다. 현재 운영 환경은 +> [`../terraform-pm/README.md`](../terraform-pm/README.md)를 사용합니다. +> 이 디렉터리는 기존 state 확인과 구 리소스 정리에만 사용하며, 운영 배포용으로 apply하지 않습니다. + +2026-11-22 기존 AfterNote 정리를 완료했습니다. 이 루트의 관리 리소스 40개를 +destroy했고, Terraform 밖의 이전 EC2/VPC, EIP, RDS 수동 스냅샷 2개, +S3, CloudFront 무료 요금제·배포·OAC·WAF도 정리했습니다. +`clog` 리소스와 개인 IAM 사용자는 유지했고 구 앱의 액세스 키는 비활성화했습니다. +로컬 state의 관리 리소스는 0개입니다. 아래 구축 절차는 과거 구성에 대한 참고용입니다. + +삭제 전 두 계정의 state·변수 백업은 Git에서 제외된 +`.retirement-backups/20261122/`에 보관합니다. 백업에는 인증정보가 포함될 수 있으므로 +외부로 공유하거나 Git에 추가하지 않습니다. + VPC / EC2 / RDS / EIP / EventBridge Scheduler(Stop·Start) / SNS 알람을 코드로 생성합니다. - **Stop** 03:00 KST · **Start** 12:00 KST diff --git a/infra/terraform/main.tf b/infra/terraform/main.tf index 49461c3..416487a 100644 --- a/infra/terraform/main.tf +++ b/infra/terraform/main.tf @@ -1,5 +1,7 @@ provider "aws" { - region = var.aws_region + region = var.aws_region + profile = "default" + allowed_account_ids = ["312871631529"] default_tags { tags = {