diff --git a/.github/workflows/cd_dev.yml b/.github/workflows/cd_dev.yml index 4da258f..b3f1a38 100644 --- a/.github/workflows/cd_dev.yml +++ b/.github/workflows/cd_dev.yml @@ -39,8 +39,6 @@ jobs: aws_secret_access_key = "${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }}" rds_username = "${{ secrets.RDS_USERNAME }}" rds_password = "${{ secrets.RDS_PASSWORD }}" - domain_name = "${{ secrets.DEV_DOMAIN_NAME }}" - email = "${{ secrets.LETSENCRYPT_EMAIL }}" EOF - name: Terraform Apply (dev) diff --git a/.github/workflows/cd_prod.yml b/.github/workflows/cd_prod.yml index 8f3dbf4..f3dab95 100644 --- a/.github/workflows/cd_prod.yml +++ b/.github/workflows/cd_prod.yml @@ -40,8 +40,6 @@ jobs: aws_secret_access_key = "${{ secrets.PROD_AWS_SECRET_ACCESS_KEY }}" rds_username = "${{ secrets.RDS_USERNAME }}" rds_password = "${{ secrets.RDS_PASSWORD }}" - domain_name = "${{ secrets.PROD_DOMAIN_NAME }}" - email = "${{ secrets.LETSENCRYPT_EMAIL }}" EOF - name: Terraform Apply (prod) diff --git a/.github/workflows/ci_dev.yml b/.github/workflows/ci_dev.yml index 0317e8a..cca18c6 100644 --- a/.github/workflows/ci_dev.yml +++ b/.github/workflows/ci_dev.yml @@ -43,8 +43,6 @@ jobs: aws_secret_access_key = "${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }}" rds_username = "${{ secrets.RDS_USERNAME }}" rds_password = "${{ secrets.RDS_PASSWORD }}" - domain_name = "${{ secrets.DEV_DOMAIN_NAME }}" - email = "${{ secrets.LETSENCRYPT_EMAIL }}" EOF - name: Terraform Plan (dev) diff --git a/.github/workflows/ci_prod.yml b/.github/workflows/ci_prod.yml index 2e1b0a3..abf0887 100644 --- a/.github/workflows/ci_prod.yml +++ b/.github/workflows/ci_prod.yml @@ -43,8 +43,6 @@ jobs: aws_secret_access_key = "${{ secrets.PROD_AWS_SECRET_ACCESS_KEY }}" rds_username = "${{ secrets.RDS_USERNAME }}" rds_password = "${{ secrets.RDS_PASSWORD }}" - domain_name = "${{ secrets.PROD_DOMAIN_NAME }}" - email = "${{ secrets.LETSENCRYPT_EMAIL }}" EOF - name: Terraform Plan (prod) diff --git a/README.md b/README.md index 37695fc..a46b6f7 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ terraform apply -var-file="terraform.tfvars" - **Route53**: DNS 관리 및 A 레코드 자동 설정 ### Security -- **Security Groups**: EC2, RDS, ALB용 보안 그룹 +- **Security Groups**: EC2, RDS용 보안 그룹 - **NACLs**: 서브넷 레벨 네트워크 제어 ### Storage diff --git a/terraform/env/dev/locals.tf b/terraform/env/dev/locals.tf index 90a9efb..a48d14c 100644 --- a/terraform/env/dev/locals.tf +++ b/terraform/env/dev/locals.tf @@ -13,13 +13,7 @@ locals { # 이름 규칙 name_prefix = "${local.environment}-clokey" - # Backend 설정 (하드코딩) - state_bucket_name = "clokey-terraform-state-116541188992" - state_key = "dev/terraform.tfstate" - - # UserData 설정 (템플릿 파일에서 변수 주입 후 base64 인코딩) - user_data_base64 = base64encode(templatefile("${path.module}/../../../userdata-examples/was-userdata-dev.sh", { - domain_name = var.domain_name - email = var.email - })) + # UserData 설정 (파일에서 base64로 인코딩하여 로드) + user_data_base64 = filebase64("${path.module}/../../../userdata-examples/was-userdata.sh") } + diff --git a/terraform/env/dev/variables.tf b/terraform/env/dev/variables.tf index 65ebfde..f0ef5e7 100644 --- a/terraform/env/dev/variables.tf +++ b/terraform/env/dev/variables.tf @@ -22,17 +22,3 @@ variable "rds_password" { type = string sensitive = true } - -variable "domain_name" { - description = "Domain name for the application (from GitHub Secrets)" - type = string - sensitive = true -} - -variable "email" { - description = "Email address for Let's Encrypt certificate (from GitHub Secrets)" - type = string - sensitive = true - default = "aa020228@gmail.com" -} - diff --git a/terraform/env/prod/locals.tf b/terraform/env/prod/locals.tf index 2d87284..7b04742 100644 --- a/terraform/env/prod/locals.tf +++ b/terraform/env/prod/locals.tf @@ -13,13 +13,7 @@ locals { # 이름 규칙 name_prefix = "${local.environment}-clokey" - # Backend 설정 (하드코딩) - state_bucket_name = "clokey-terraform-state-116541188992" - state_key = "prod/terraform.tfstate" - - # UserData 설정 (템플릿 파일에서 변수 주입 후 base64 인코딩) - user_data_base64 = base64encode(templatefile("${path.module}/../../../userdata-examples/was-userdata-prod.sh", { - domain_name = var.domain_name - email = var.email - })) + # UserData 설정 (파일에서 base64로 인코딩하여 로드) + user_data_base64 = filebase64("${path.module}/../../../userdata-examples/was-userdata.sh") } + diff --git a/terraform/env/prod/variables.tf b/terraform/env/prod/variables.tf index ae7f081..943f958 100644 --- a/terraform/env/prod/variables.tf +++ b/terraform/env/prod/variables.tf @@ -23,17 +23,3 @@ variable "rds_password" { type = string sensitive = true } - -variable "domain_name" { - description = "Domain name for the application (from GitHub Secrets)" - type = string - sensitive = true -} - -variable "email" { - description = "Email address for Let's Encrypt certificate (from GitHub Secrets)" - type = string - sensitive = true - default = "aa020228@gmail.com" -} - diff --git a/terraform/modules/network/alb/main.tf b/terraform/modules/network/alb/main.tf deleted file mode 100644 index c9ca146..0000000 --- a/terraform/modules/network/alb/main.tf +++ /dev/null @@ -1,100 +0,0 @@ -resource "aws_lb" "main" { - name = "${var.name_prefix}-alb" - internal = var.internal - load_balancer_type = "application" - security_groups = var.security_groups - subnets = var.subnet_ids - - enable_deletion_protection = var.enable_deletion_protection - - access_logs { - bucket = var.access_logs_bucket - prefix = var.access_logs_prefix - enabled = var.enable_access_logs - } - - tags = merge(var.tags, { - Name = "${var.name_prefix}-alb" - }) -} - -resource "aws_lb_target_group" "main" { - name = "${var.name_prefix}-tg" - port = var.target_group_port - protocol = var.target_group_protocol - vpc_id = var.vpc_id - - health_check { - enabled = true - healthy_threshold = var.health_check_healthy_threshold - unhealthy_threshold = var.health_check_unhealthy_threshold - timeout = var.health_check_timeout - interval = var.health_check_interval - path = var.health_check_path - matcher = var.health_check_matcher - port = var.health_check_port - protocol = var.health_check_protocol - } - - tags = merge(var.tags, { - Name = "${var.name_prefix}-tg" - }) -} - -resource "aws_lb_listener" "http" { - count = var.create_http_listener ? 1 : 0 - - load_balancer_arn = aws_lb.main.arn - port = "80" - protocol = "HTTP" - - default_action { - type = var.http_listener_action_type - target_group_arn = var.http_listener_action_type == "forward" ? aws_lb_target_group.main.arn : null - - dynamic "redirect" { - for_each = var.http_listener_action_type == "redirect" ? [1] : [] - content { - port = "443" - protocol = "HTTPS" - status_code = "HTTP_301" - } - } - } -} - -resource "aws_lb_listener" "https" { - count = var.create_https_listener ? 1 : 0 - - load_balancer_arn = aws_lb.main.arn - port = "443" - protocol = "HTTPS" - ssl_policy = var.ssl_policy - certificate_arn = var.certificate_arn - - default_action { - type = "forward" - target_group_arn = aws_lb_target_group.main.arn - } - - # 인증서가 완전히 검증된 후에 리스너 생성 - depends_on = [var.certificate_arn] -} - -resource "aws_lb_listener_rule" "main" { - count = length(var.listener_rules) - - listener_arn = var.create_https_listener ? aws_lb_listener.https[0].arn : aws_lb_listener.http[0].arn - priority = var.listener_rules[count.index].priority - - action { - type = "forward" - target_group_arn = aws_lb_target_group.main.arn - } - - condition { - path_pattern { - values = var.listener_rules[count.index].path_patterns - } - } -} diff --git a/terraform/modules/network/alb/output.tf b/terraform/modules/network/alb/output.tf deleted file mode 100644 index 974ca06..0000000 --- a/terraform/modules/network/alb/output.tf +++ /dev/null @@ -1,34 +0,0 @@ -output "load_balancer_arn" { - description = "ARN of the load balancer" - value = aws_lb.main.arn -} - -output "load_balancer_dns_name" { - description = "DNS name of the load balancer" - value = aws_lb.main.dns_name -} - -output "load_balancer_zone_id" { - description = "Zone ID of the load balancer" - value = aws_lb.main.zone_id -} - -output "target_group_arn" { - description = "ARN of the target group" - value = aws_lb_target_group.main.arn -} - -output "target_group_name" { - description = "Name of the target group" - value = aws_lb_target_group.main.name -} - -output "http_listener_arn" { - description = "ARN of the HTTP listener" - value = var.create_http_listener ? aws_lb_listener.http[0].arn : null -} - -output "https_listener_arn" { - description = "ARN of the HTTPS listener" - value = var.create_https_listener ? aws_lb_listener.https[0].arn : null -} diff --git a/terraform/modules/network/alb/variables.tf b/terraform/modules/network/alb/variables.tf deleted file mode 100644 index 2728366..0000000 --- a/terraform/modules/network/alb/variables.tf +++ /dev/null @@ -1,158 +0,0 @@ -variable "name_prefix" { - description = "Name prefix for resources" - type = string -} - -variable "internal" { - description = "Whether the load balancer is internal" - type = bool - default = false -} - -variable "security_groups" { - description = "List of security group IDs for the load balancer" - type = list(string) -} - -variable "subnet_ids" { - description = "List of subnet IDs for the load balancer" - type = list(string) -} - -variable "vpc_id" { - description = "VPC ID where the load balancer will be created" - type = string -} - -variable "enable_deletion_protection" { - description = "Enable deletion protection for the load balancer" - type = bool - default = false -} - -variable "access_logs_bucket" { - description = "S3 bucket for access logs" - type = string - default = "" -} - -variable "access_logs_prefix" { - description = "S3 prefix for access logs" - type = string - default = "" -} - -variable "enable_access_logs" { - description = "Enable access logs" - type = bool - default = false -} - -variable "target_group_port" { - description = "Port for the target group" - type = number - default = 80 -} - -variable "target_group_protocol" { - description = "Protocol for the target group" - type = string - default = "HTTP" -} - -variable "health_check_healthy_threshold" { - description = "Number of consecutive health checks successes required" - type = number - default = 2 -} - -variable "health_check_unhealthy_threshold" { - description = "Number of consecutive health check failures required" - type = number - default = 2 -} - -variable "health_check_timeout" { - description = "Amount of time to wait when receiving a response from a health check" - type = number - default = 5 -} - -variable "health_check_interval" { - description = "Approximate amount of time between health checks" - type = number - default = 30 -} - -variable "health_check_path" { - description = "Destination for the health check request" - type = string - default = "/" -} - -variable "health_check_matcher" { - description = "HTTP codes to use when checking for a successful response" - type = string - default = "200" -} - -variable "health_check_port" { - description = "Port to use to connect with the target" - type = string - default = "traffic-port" -} - -variable "health_check_protocol" { - description = "Protocol to use to connect with the target" - type = string - default = "HTTP" -} - -variable "create_http_listener" { - description = "Whether to create HTTP listener" - type = bool - default = true -} - -variable "http_listener_action_type" { - description = "Action type for HTTP listener: 'forward' or 'redirect'" - type = string - default = "redirect" - validation { - condition = contains(["forward", "redirect"], var.http_listener_action_type) - error_message = "http_listener_action_type must be either 'forward' or 'redirect'." - } -} - -variable "create_https_listener" { - description = "Whether to create HTTPS listener" - type = bool - default = true -} - -variable "ssl_policy" { - description = "SSL policy for HTTPS listener" - type = string - default = "ELBSecurityPolicy-TLS-1-2-2017-01" -} - -variable "certificate_arn" { - description = "ARN of the SSL certificate for HTTPS listener" - type = string - default = "" -} - -variable "listener_rules" { - description = "List of listener rules" - type = list(object({ - priority = number - path_patterns = list(string) - })) - default = [] -} - -variable "tags" { - description = "Tags to apply to resources" - type = map(string) - default = {} -} diff --git a/userdata-examples/was-userdata-dev.sh b/userdata-examples/was-userdata-dev.sh deleted file mode 100644 index 68c1f22..0000000 --- a/userdata-examples/was-userdata-dev.sh +++ /dev/null @@ -1,220 +0,0 @@ -#!/bin/bash - -# UserData 스크립트 실행 권한 확인 및 설정 -chmod +x "$0" - -# 로그 파일 설정 -LOG_FILE="/var/log/userdata.log" -exec > >(tee -a $LOG_FILE) 2>&1 - -echo "==========================================" -echo "UserData 스크립트 시작: $(date)" -echo "환경: DEV" -echo "==========================================" - -# 환경 변수 설정 (Terraform 템플릿 변수에서 주입) -DOMAIN_NAME="${domain_name}" -EMAIL="${email}" - -# 시스템 업데이트 -echo "시스템 업데이트 시작..." -sudo apt update -y -sudo apt upgrade -y - -# Java 21 설치 -echo "Java 21 설치 중..." -sudo apt install -y openjdk-21-jdk - -# MySQL 클라이언트 설치 -sudo apt install -y mysql-client-core-8.0 - -# Docker 설치 -echo "Docker 설치 중..." -sudo apt install -y docker.io -sudo systemctl start docker -sudo systemctl enable docker - -# Docker Compose v2 설치 -echo "Docker Compose v2 설치 중..." -mkdir -p ~/.docker/cli-plugins/ -curl -SL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-x86_64 -o ~/.docker/cli-plugins/docker-compose -chmod +x ~/.docker/cli-plugins/docker-compose - -# Nginx 설치 -echo "Nginx 설치 중..." -sudo apt install -y nginx -sudo systemctl start nginx -sudo systemctl enable nginx - -# Certbot 설치 (Let's Encrypt) -echo "Certbot 설치 중..." -sudo apt install -y certbot python3-certbot-nginx - -# Nginx 기본 설정 파일 백업 -echo "Nginx 설정 파일 백업 중..." -sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup - -# Nginx 기본 설정 (sites-enabled 방식 사용) -echo "Nginx 기본 설정 생성 중..." -sudo tee /etc/nginx/nginx.conf > /dev/null << 'NGINXCONF' -user www-data; -worker_processes auto; -pid /run/nginx.pid; -error_log /var/log/nginx/error.log; -include /etc/nginx/modules-enabled/*.conf; - -events { - worker_connections 768; -} - -http { - sendfile on; - tcp_nopush on; - types_hash_max_size 2048; - include /etc/nginx/mime.types; - default_type application/octet-stream; - - ssl_protocols TLSv1.2 TLSv1.3; - ssl_prefer_server_ciphers on; - - access_log /var/log/nginx/access.log; - error_log /var/log/nginx/error.log; - - gzip on; - - include /etc/nginx/conf.d/*.conf; - include /etc/nginx/sites-enabled/*; - - client_max_body_size 100M; -} -NGINXCONF - -# sites-available 디렉토리 생성 -sudo mkdir -p /etc/nginx/sites-available -sudo mkdir -p /etc/nginx/sites-enabled - -# HTTP 서버 설정 (Let's Encrypt 인증 및 리버스 프록시) -echo "Nginx HTTP 서버 설정 생성 중..." -sudo tee /etc/nginx/sites-available/${DOMAIN_NAME} > /dev/null << EOF -server { - listen 80; - server_name ${DOMAIN_NAME}; - - # Let's Encrypt 인증을 위한 경로 - location /.well-known/acme-challenge/ { - root /var/www/html; - } - - # 리버스 프록시 설정 - location / { - proxy_pass http://localhost:8080; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host \$host; - proxy_set_header X-Real-IP \$remote_addr; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto \$scheme; - } -} -EOF - -# sites-enabled에 심볼릭 링크 생성 -sudo ln -sf /etc/nginx/sites-available/${DOMAIN_NAME} /etc/nginx/sites-enabled/ - -# Nginx 설정 테스트 및 재시작 -echo "Nginx 설정 테스트 중..." -sudo nginx -t -if [ $? -eq 0 ]; then - sudo systemctl restart nginx - echo "✅ Nginx 재시작 완료" -else - echo "❌ Nginx 설정 테스트 실패" - sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf - sudo systemctl restart nginx -fi - -# Let's Encrypt 인증서 발급 스크립트 생성 -echo "Let's Encrypt 인증서 발급 스크립트 생성 중..." -cat > /root/get-ssl-cert.sh << CERTSCRIPT -#!/bin/bash -DOMAIN_NAME="${DOMAIN_NAME}" -EMAIL="${EMAIL}" - -echo "SSL 인증서 발급 시작: \${DOMAIN_NAME}" - -# certbot이 nginx 설정을 자동으로 업데이트하도록 실행 -# --nginx 플러그인은 자동으로 HTTPS 블록을 추가하고 HTTP를 HTTPS로 리다이렉트합니다 -sudo certbot --nginx \ - -d \${DOMAIN_NAME} \ - --non-interactive \ - --agree-tos \ - --email \${EMAIL} \ - --redirect \ - --keep-until-expiring - -# 인증서 자동 갱신 설정 -sudo systemctl enable certbot.timer -sudo systemctl start certbot.timer - -echo "✅ SSL 인증서 발급 완료" -echo "✅ Nginx 설정이 자동으로 업데이트되었습니다" -CERTSCRIPT - -chmod +x /root/get-ssl-cert.sh - -# Swap 메모리 설정 (2GB) -echo "Swap 메모리 설정 중..." -sudo fallocate -l 2G /swapfile -sudo chmod 600 /swapfile -sudo mkswap /swapfile -sudo swapon /swapfile -echo '/swapfile none swap sw 0 0' >> /etc/fstab - -# Redis 컨테이너 실행 -echo "Redis 컨테이너 시작 중..." -sudo docker run -d \ - --name redis-container \ - --restart unless-stopped \ - -p 6379:6379 \ - redis:latest - -# EC2 재시작 시 자동 설정을 위한 systemd 서비스 생성 -cat > /etc/systemd/system/clokey-setup.service << 'EOF' -[Unit] -Description=Clokey Application Setup -After=docker.service -Requires=docker.service - -[Service] -Type=oneshot -RemainAfterExit=yes -ExecStart=/bin/bash -c ' - if ! swapon --show | grep -q /swapfile; then - swapon /swapfile - fi - if ! docker ps --format "table {{.Names}}" | grep -q redis-container; then - docker start redis-container 2>/dev/null || docker run -d --name redis-container --restart unless-stopped -p 6379:6379 redis:latest - fi -' - -[Install] -WantedBy=multi-user.target -EOF - -systemctl daemon-reload -systemctl enable clokey-setup.service - -# 설치 완료 메시지 -echo "==========================================" -echo "WAS 서버 초기 설정 완료!" -echo "환경: DEV" -echo "도메인: ${DOMAIN_NAME}" -echo "==========================================" -echo "SSL 인증서 발급 방법:" -echo "1. 도메인이 이 서버의 퍼블릭 IP를 가리키도록 설정" -echo "2. 다음 명령어 실행: sudo /root/get-ssl-cert.sh" -echo "==========================================" -echo "UserData 스크립트 완료: $(date)" -echo "로그 파일 위치: $LOG_FILE" -echo "==========================================" - diff --git a/userdata-examples/was-userdata-prod.sh b/userdata-examples/was-userdata-prod.sh deleted file mode 100644 index 1f496a0..0000000 --- a/userdata-examples/was-userdata-prod.sh +++ /dev/null @@ -1,220 +0,0 @@ -#!/bin/bash - -# UserData 스크립트 실행 권한 확인 및 설정 -chmod +x "$0" - -# 로그 파일 설정 -LOG_FILE="/var/log/userdata.log" -exec > >(tee -a $LOG_FILE) 2>&1 - -echo "==========================================" -echo "UserData 스크립트 시작: $(date)" -echo "환경: PROD" -echo "==========================================" - -# 환경 변수 설정 (Terraform 템플릿 변수에서 주입) -DOMAIN_NAME="${domain_name}" -EMAIL="${email}" - -# 시스템 업데이트 -echo "시스템 업데이트 시작..." -sudo apt update -y -sudo apt upgrade -y - -# Java 21 설치 -echo "Java 21 설치 중..." -sudo apt install -y openjdk-21-jdk - -# MySQL 클라이언트 설치 -sudo apt install -y mysql-client-core-8.0 - -# Docker 설치 -echo "Docker 설치 중..." -sudo apt install -y docker.io -sudo systemctl start docker -sudo systemctl enable docker - -# Docker Compose v2 설치 -echo "Docker Compose v2 설치 중..." -mkdir -p ~/.docker/cli-plugins/ -curl -SL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-x86_64 -o ~/.docker/cli-plugins/docker-compose -chmod +x ~/.docker/cli-plugins/docker-compose - -# Nginx 설치 -echo "Nginx 설치 중..." -sudo apt install -y nginx -sudo systemctl start nginx -sudo systemctl enable nginx - -# Certbot 설치 (Let's Encrypt) -echo "Certbot 설치 중..." -sudo apt install -y certbot python3-certbot-nginx - -# Nginx 기본 설정 파일 백업 -echo "Nginx 설정 파일 백업 중..." -sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup - -# Nginx 기본 설정 (sites-enabled 방식 사용) -echo "Nginx 기본 설정 생성 중..." -sudo tee /etc/nginx/nginx.conf > /dev/null << 'NGINXCONF' -user www-data; -worker_processes auto; -pid /run/nginx.pid; -error_log /var/log/nginx/error.log; -include /etc/nginx/modules-enabled/*.conf; - -events { - worker_connections 768; -} - -http { - sendfile on; - tcp_nopush on; - types_hash_max_size 2048; - include /etc/nginx/mime.types; - default_type application/octet-stream; - - ssl_protocols TLSv1.2 TLSv1.3; - ssl_prefer_server_ciphers on; - - access_log /var/log/nginx/access.log; - error_log /var/log/nginx/error.log; - - gzip on; - - include /etc/nginx/conf.d/*.conf; - include /etc/nginx/sites-enabled/*; - - client_max_body_size 100M; -} -NGINXCONF - -# sites-available 디렉토리 생성 -sudo mkdir -p /etc/nginx/sites-available -sudo mkdir -p /etc/nginx/sites-enabled - -# HTTP 서버 설정 (Let's Encrypt 인증 및 리버스 프록시) -echo "Nginx HTTP 서버 설정 생성 중..." -sudo tee /etc/nginx/sites-available/${DOMAIN_NAME} > /dev/null << EOF -server { - listen 80; - server_name ${DOMAIN_NAME}; - - # Let's Encrypt 인증을 위한 경로 - location /.well-known/acme-challenge/ { - root /var/www/html; - } - - # 리버스 프록시 설정 - location / { - proxy_pass http://localhost:8080; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host \$host; - proxy_set_header X-Real-IP \$remote_addr; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto \$scheme; - } -} -EOF - -# sites-enabled에 심볼릭 링크 생성 -sudo ln -sf /etc/nginx/sites-available/${DOMAIN_NAME} /etc/nginx/sites-enabled/ - -# Nginx 설정 테스트 및 재시작 -echo "Nginx 설정 테스트 중..." -sudo nginx -t -if [ $? -eq 0 ]; then - sudo systemctl restart nginx - echo "✅ Nginx 재시작 완료" -else - echo "❌ Nginx 설정 테스트 실패" - sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf - sudo systemctl restart nginx -fi - -# Let's Encrypt 인증서 발급 스크립트 생성 -echo "Let's Encrypt 인증서 발급 스크립트 생성 중..." -cat > /root/get-ssl-cert.sh << CERTSCRIPT -#!/bin/bash -DOMAIN_NAME="${DOMAIN_NAME}" -EMAIL="${EMAIL}" - -echo "SSL 인증서 발급 시작: \${DOMAIN_NAME}" - -# certbot이 nginx 설정을 자동으로 업데이트하도록 실행 -# --nginx 플러그인은 자동으로 HTTPS 블록을 추가하고 HTTP를 HTTPS로 리다이렉트합니다 -sudo certbot --nginx \ - -d \${DOMAIN_NAME} \ - --non-interactive \ - --agree-tos \ - --email \${EMAIL} \ - --redirect \ - --keep-until-expiring - -# 인증서 자동 갱신 설정 -sudo systemctl enable certbot.timer -sudo systemctl start certbot.timer - -echo "✅ SSL 인증서 발급 완료" -echo "✅ Nginx 설정이 자동으로 업데이트되었습니다" -CERTSCRIPT - -chmod +x /root/get-ssl-cert.sh - -# Swap 메모리 설정 (2GB) -echo "Swap 메모리 설정 중..." -sudo fallocate -l 2G /swapfile -sudo chmod 600 /swapfile -sudo mkswap /swapfile -sudo swapon /swapfile -echo '/swapfile none swap sw 0 0' >> /etc/fstab - -# Redis 컨테이너 실행 -echo "Redis 컨테이너 시작 중..." -sudo docker run -d \ - --name redis-container \ - --restart unless-stopped \ - -p 6379:6379 \ - redis:latest - -# EC2 재시작 시 자동 설정을 위한 systemd 서비스 생성 -cat > /etc/systemd/system/clokey-setup.service << 'EOF' -[Unit] -Description=Clokey Application Setup -After=docker.service -Requires=docker.service - -[Service] -Type=oneshot -RemainAfterExit=yes -ExecStart=/bin/bash -c ' - if ! swapon --show | grep -q /swapfile; then - swapon /swapfile - fi - if ! docker ps --format "table {{.Names}}" | grep -q redis-container; then - docker start redis-container 2>/dev/null || docker run -d --name redis-container --restart unless-stopped -p 6379:6379 redis:latest - fi -' - -[Install] -WantedBy=multi-user.target -EOF - -systemctl daemon-reload -systemctl enable clokey-setup.service - -# 설치 완료 메시지 -echo "==========================================" -echo "WAS 서버 초기 설정 완료!" -echo "환경: PROD" -echo "도메인: ${DOMAIN_NAME}" -echo "==========================================" -echo "SSL 인증서 발급 방법:" -echo "1. 도메인이 이 서버의 퍼블릭 IP를 가리키도록 설정" -echo "2. 다음 명령어 실행: sudo /root/get-ssl-cert.sh" -echo "==========================================" -echo "UserData 스크립트 완료: $(date)" -echo "로그 파일 위치: $LOG_FILE" -echo "==========================================" - diff --git a/userdata-examples/was-userdata.sh b/userdata-examples/was-userdata.sh index a58e876..ab9cbbe 100644 --- a/userdata-examples/was-userdata.sh +++ b/userdata-examples/was-userdata.sh @@ -93,130 +93,6 @@ else echo "❌ Nginx 서비스 시작 실패" fi -# Nginx 설정 파일 백업 -echo "Nginx 설정 파일 백업 중..." -sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup -if [ $? -eq 0 ]; then - echo "✅ Nginx 설정 파일 백업 완료" -else - echo "❌ Nginx 설정 파일 백업 실패" -fi - -# Nginx 설정 파일 생성 -echo "Nginx 설정 파일 생성 중..." -sudo tee /etc/nginx/nginx.conf > /dev/null << 'EOF' -user www-data; -worker_processes auto; -pid /run/nginx.pid; -error_log /var/log/nginx/error.log; -include /etc/nginx/modules-enabled/*.conf; - -events { - worker_connections 768; - # multi_accept on; -} - -http { - server { - listen 80; - server_name prod.clokey.store; - return 301 https://$host$request_uri; - } - - server { - listen 443 ssl; - server_name prod.clokey.store; - ssl_certificate /etc/letsencrypt/live/prod.clokey.store/fullch - ssl_certificate_key /etc/letsencrypt/live/prod.clokey.store/pr - include /etc/letsencrypt/options-ssl-nginx.conf; - ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; - location / { - proxy_pass http://localhost:8080; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_> - } - } - - ## - # Basic Settings - ## - - sendfile on; - tcp_nopush on; - types_hash_max_size 2048; - # server_tokens off; - - # server_names_hash_bucket_size 64; - # server_name_in_redirect off; - - include /etc/nginx/mime.types; - default_type application/octet-stream; - - ## - # SSL Settings - ## - - ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE - ssl_prefer_server_ciphers on; - - ## - # Logging Settings - ## - - access_log /var/log/nginx/access.log; - - ## - # Gzip Settings - ## - - gzip on; - - # gzip_vary on; - # gzip_proxied any; - # gzip_comp_level 6; - # gzip_buffers 16 8k; - # gzip_http_version 1.1; - # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; - - ## - # Virtual Host Configs - ## - - include /etc/nginx/conf.d/*.conf; - include /etc/nginx/sites-enabled/*; - - client_max_body_size 100M; -} -EOF - -if [ $? -eq 0 ]; then - echo "✅ Nginx 설정 파일 생성 완료" -else - echo "❌ Nginx 설정 파일 생성 실패" -fi - -# Nginx 설정 테스트 -echo "Nginx 설정 테스트 중..." -sudo nginx -t -if [ $? -eq 0 ]; then - echo "✅ Nginx 설정 테스트 성공" - # Nginx 재시작 - sudo systemctl restart nginx - if [ $? -eq 0 ]; then - echo "✅ Nginx 재시작 완료" - else - echo "❌ Nginx 재시작 실패" - fi -else - echo "❌ Nginx 설정 테스트 실패" - # 백업 파일로 복원 - sudo cp /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf - sudo systemctl restart nginx -fi - # Swap 메모리 설정 (2GB) echo "Swap 메모리 설정 중..." sudo fallocate -l 2G /swapfile