Skip to content

cloud-wave-best-zizon/aws-infra-terraform

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AWS MSA Infrastructure with Terraform

Production-ready AWS 인프라를 Terraform으로 구축하는 프로젝트입니다. Dev/Prod 환경을 분리하고, 비용 최적화와 확장성을 고려한 설계입니다.

📋 목차

🏗 아키텍처 개요

전체 구조

┌─────────────────────────────────────────────────────────────┐
│                         AWS Account                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────────────┐    ┌──────────────────────┐     │
│  │      Dev VPC         │    │      Prod VPC        │     │
│  │   10.0.0.0/16       │<-->│    10.1.0.0/16      │     │
│  │                     │    │                      │     │
│  │  ┌──────────────┐  │    │  ┌──────────────┐  │     │
│  │  │ EKS Cluster  │  │    │  │ EKS Cluster  │  │     │
│  │  │   (Spot)     │  │    │  │ (On-Demand)  │  │     │
│  │  └──────────────┘  │    │  └──────────────┘  │     │
│  │                     │    │                      │     │
│  │  NAT Instance      │    │  NAT Gateway        │     │
│  │  (t3.nano)         │    │  (Multi-AZ)         │     │
│  └──────────────────────┘    └──────────────────────┘     │
│                                                             │
│  ┌────────────────────────────────────────────────────┐   │
│  │              DynamoDB Tables                        │   │
│  │  • dev-products  • dev-orders                      │   │
│  │  • prod-products • prod-orders                     │   │
│  └────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

네트워크 구성

Dev VPC (10.0.0.0/16)

  • Public Subnet: 10.0.1.0/24 (AZ-A)
    • NAT Instance
    • Bastion Host (선택사항)
  • Private Subnet: 10.0.11.0/24 (AZ-A)
    • EKS Worker Nodes
    • Application Services

Prod VPC (10.1.0.0/16)

  • Public Subnets:
    • 10.1.1.0/24 (AZ-A) - ALB, NAT Gateway
    • 10.1.2.0/24 (AZ-C) - 부하테스트시 활성화
  • Private Subnets:
    • 10.1.11.0/24 (AZ-A) - EKS Worker Nodes
    • 10.1.12.0/24 (AZ-C) - 부하테스트시 확장

✨ 주요 기능

1. 환경 분리

  • Dev/Prod 완전 분리된 VPC
  • VPC Peering을 통한 선택적 연결
  • 환경별 보안 그룹 및 IAM 역할

2. 비용 최적화

  • Dev: Spot Instance, NAT Instance, NodePort 사용
  • Prod: On-Demand Instance, 필요시만 Multi-AZ
  • VPC Endpoints로 트래픽 비용 절감
  • DynamoDB On-Demand 모드

3. 확장성

  • HPA (Horizontal Pod Autoscaler) 지원
  • Cluster Autoscaler 지원
  • 부하테스트 모드 (Multi-AZ 자동 활성화)

4. 보안

  • Private Subnets의 EKS Nodes
  • VPC Endpoints로 AWS 서비스 접근
  • IAM Role 기반 권한 관리
  • Security Groups 세분화

📦 사전 요구사항

필수 도구

# Terraform (>= 1.0)
brew install terraform

# AWS CLI
brew install awscli

# kubectl
brew install kubectl

# eksctl (선택사항)
brew install eksctl

AWS 설정

# AWS 자격 증명 설정
aws configure

# 또는 환경 변수
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"
export AWS_REGION="ap-northeast-2"

📁 프로젝트 구조

terraform-aws-msa/
├── main.tf                 # 메인 설정
├── variables.tf           # 변수 정의
├── outputs.tf            # 출력 값
├── peering.tf           # VPC Peering
├── dynamodb.tf          # DynamoDB 테이블
├── route53.tf           # DNS 설정
├── environments/
│   ├── dev.tf          # Dev 환경 구성
│   └── prod.tf         # Prod 환경 구성
├── modules/
│   ├── vpc/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── outputs.tf
│   └── eks/
│       ├── main.tf
│       ├── variables.tf
│       ├── outputs.tf
│       └── policies/
│           └── alb-controller-policy.json
└── terraform.tfvars.example

🚀 빠른 시작

1. 프로젝트 클론 및 설정

# 프로젝트 클론
git clone https://github.com/your-repo/terraform-aws-msa.git
cd terraform-aws-msa

# terraform.tfvars 생성
cp terraform.tfvars.example terraform.tfvars

2. terraform.tfvars 편집

# terraform.tfvars
aws_region = "ap-northeast-2"

# Dev EKS 설정
dev_eks_config = {
  cluster_name    = "dev-msa-cluster"
  cluster_version = "1.28"
  instance_types  = ["t3.small"]
  capacity_type   = "SPOT"
  min_size        = 1
  max_size        = 2
  desired_size    = 1
}

# Prod EKS 설정
prod_eks_config = {
  cluster_name    = "prod-msa-cluster"
  cluster_version = "1.28"
  instance_types  = ["t3.medium"]
  capacity_type   = "ON_DEMAND"
  min_size        = 2
  max_size        = 4
  desired_size    = 2
}

# 도메인 설정 (선택사항)
domain_name = "example.com"
create_public_zone = false

# 부하 테스트 모드
enable_load_testing = false

3. Terraform 실행

# 초기화
terraform init

# 계획 검토
terraform plan

# 인프라 생성
terraform apply

# 특정 환경만 생성
terraform apply -target=module.dev_vpc -target=module.dev_eks

4. kubeconfig 설정

# Dev 클러스터
aws eks update-kubeconfig --region ap-northeast-2 --name dev-msa-cluster

# Prod 클러스터
aws eks update-kubeconfig --region ap-northeast-2 --name prod-msa-cluster

# 컨텍스트 확인
kubectl config get-contexts

🔧 환경별 구성

Dev 환경 특징

# NodePort 서비스로 접근
kubectl get nodes -o wide
# NODE_IP 확인 후
curl http://<NODE_IP>:30001/health

# 비용: 약 $21.5/월
# - EKS Nodes (Spot): ~$18
# - NAT Instance: ~$3.5

Prod 환경 특징

# ALB를 통한 접근
terraform output prod_alb_dns
# https://prod-msa-alb-xxx.ap-northeast-2.elb.amazonaws.com

# 비용: 약 $165.6/월 (평시)
# - EKS Nodes: ~$74
# - NAT Gateway: ~$45
# - ALB: ~$25
# - VPC Endpoints: ~$21.6

부하 테스트 모드 활성화

# terraform.tfvars에서 enable_load_testing = true 설정
terraform apply -var="enable_load_testing=true"

# Multi-AZ 구성 활성화
# 비용: 약 $284.6/월로 증가

💰 비용 최적화

1. Dev 환경 절감 방안

# 사용하지 않을 때 중지
terraform destroy -target=module.dev_eks

# Spot Instance 활용
capacity_type = "SPOT"

# NAT Instance 사용 (NAT Gateway 대비 90% 절감)
create_nat_instance = true

2. Prod 환경 절감 방안

# 평시 Single-AZ 운영
enable_load_testing = false

# Reserved Instance 구매 고려
# 1년 약정시 30-40% 절감

# DynamoDB On-Demand 모드
billing_mode = "PAY_PER_REQUEST"

3. 전체 비용 모니터링

# AWS Cost Explorer 활용
aws ce get-cost-and-usage \
  --time-period Start=2024-01-01,End=2024-01-31 \
  --granularity MONTHLY \
  --metrics "UnblendedCost" \
  --group-by Type=DIMENSION,Key=SERVICE

📖 운영 가이드

애플리케이션 배포

# Dev 환경 배포
kubectl config use-context dev-msa-cluster
kubectl apply -f k8s/dev/

# Prod 환경 배포
kubectl config use-context prod-msa-cluster
kubectl apply -f k8s/prod/

모니터링

# CloudWatch Container Insights 활성화
aws eks update-cluster-config \
  --name prod-msa-cluster \
  --logging '{"clusterLogging":[{"types":["api","audit","authenticator","controllerManager","scheduler"],"enabled":true}]}'

# 메트릭 확인
kubectl top nodes
kubectl top pods

백업 및 복구

# DynamoDB 백업
aws dynamodb create-backup \
  --table-name prod-products-table \
  --backup-name prod-products-backup-$(date +%Y%m%d)

# EKS 설정 백업
kubectl get all --all-namespaces -o yaml > backup.yaml

🔨 문제 해결

일반적인 문제

1. EKS 노드가 Ready 상태가 아님

# 노드 상태 확인
kubectl describe node <node-name>

# Security Group 확인
aws ec2 describe-security-groups --group-ids <sg-id>

# IAM Role 확인
aws iam get-role --role-name <cluster-name>-node-group-role

2. VPC Peering 연결 안됨

# Peering 상태 확인
aws ec2 describe-vpc-peering-connections

# Route Table 확인
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=<vpc-id>"

3. DynamoDB 접근 오류

# VPC Endpoint 확인
aws ec2 describe-vpc-endpoints --filters "Name=vpc-id,Values=<vpc-id>"

# IAM Policy 확인
aws iam get-role-policy --role-name <node-role> --policy-name dynamodb-access

롤백

# 이전 상태로 롤백
terraform apply -target=<resource> -replace=<resource>

# 전체 삭제 (주의!)
terraform destroy

📊 메트릭 및 알람

CloudWatch 알람 설정

# CPU 사용률 알람
aws cloudwatch put-metric-alarm \
  --alarm-name eks-cpu-high \
  --alarm-description "EKS Node CPU usage" \
  --metric-name CPUUtilization \
  --namespace AWS/EC2 \
  --statistic Average \
  --period 300 \
  --threshold 80 \
  --comparison-operator GreaterThanThreshold

🔐 보안 고려사항

  1. 최소 권한 원칙: IAM Role은 필요한 최소 권한만 부여
  2. 네트워크 격리: Private Subnet 사용, Security Group 세분화
  3. 암호화: DynamoDB 암호화, EKS Secret 암호화
  4. 감사: CloudTrail, VPC Flow Logs 활성화

📚 참고 자료

📝 라이선스

MIT License

🤝 기여

Pull Request와 Issue를 환영합니다!

📞 지원

문제가 있으시면 Issue를 생성해주세요.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages