초보자를 위한 YAML 완전 가이드 - glasslego/getting-started-with-python GitHub Wiki

🤔 YAML이 뭐야?

YAML = YAML Ain't Markup Language
"야믈"이라고 읽어요!

  • 설정 파일을 작성할 때 사용하는 언어
  • 사람이 읽기 쉽게 만들어진 데이터 형식
  • JSON, XML보다 훨씬 간단하고 깔끔

어디서 사용하나요?

  • GitHub Actions (.yml 파일)
  • Docker Compose (docker-compose.yml)
  • Kubernetes 설정
  • CI/CD 파이프라인
  • 각종 애플리케이션 설정 파일

📏 YAML의 핵심 규칙

1️⃣ 들여쓰기가 매우 중요!

# ✅ 올바른 예
parent:
  child1: value1
  child2: value2

# ❌ 잘못된 예 (들여쓰기 불일치)
parent:
  child1: value1
    child2: value2  # 들여쓰기가 다름!

2️⃣ 스페이스만 사용 (탭 금지)

# ✅ 2칸 또는 4칸 스페이스 사용
name: John
age: 30

# ❌ 탭 사용하면 안 됨!

3️⃣ 콜론 뒤에는 반드시 공백

# ✅ 올바른 예
name: John
city: Seoul

# ❌ 잘못된 예
name:John    # 공백 없음
city :Seoul  # 콜론 앞에 공백

📚 YAML 기본 문법

1. 기본 값 (Key-Value)

# 문자열
name: "홍길동"
nickname: 길동이  # 따옴표 없어도 됨

# 숫자
age: 25
height: 175.5

# 불린 (참/거짓)
is_student: true
is_married: false

# null 값
middle_name: null
# 또는
middle_name: ~

2. 리스트 (배열)

# 방법 1: 대시(-)로 표현
fruits:
  - apple
  - banana
  - orange

# 방법 2: 한 줄로 표현
colors: [red, green, blue]

# 숫자 리스트
scores:
  - 85
  - 92
  - 78

3. 객체 (중첩 구조)

person:
  name: 김철수
  age: 30
  address:
    city: 서울
    district: 강남구
    zipcode: "06234"

# 한 줄로도 가능
person: {name: 김철수, age: 30}

4. 리스트 안에 객체

students:
  - name: 김학생
    grade: A
    subjects: [수학, 영어]
  
  - name: 이학생
    grade: B
    subjects: [과학, 국어]

5. 주석

# 이것은 주석입니다
name: John  # 줄 끝에도 주석 가능

# 여러 줄 주석도 가능
# 각 줄마다 #을 붙여야 함
age: 25

🌟 실용적인 YAML 예시들

📂 1. GitHub Actions 설정

# .github/workflows/ci.yml
name: CI Pipeline

# 언제 실행할지
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

# 실행할 작업들
jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
      - name: 코드 체크아웃
        uses: actions/checkout@v4
      
      - name: Python 설정
        uses: actions/setup-python@v4
        with:
          python-version: "3.11"
      
      - name: 의존성 설치
        run: |
          pip install -r requirements.txt
      
      - name: 테스트 실행
        run: pytest

🐳 2. Docker Compose 설정

# docker-compose.yml
version: "3.8"

services:
  # 웹 애플리케이션
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DEBUG=true
      - DATABASE_URL=postgresql://user:pass@db:5432/myapp
    depends_on:
      - db
      - redis
  
  # 데이터베이스
  db:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - postgres_data:/var/lib/postgresql/data
  
  # 캐시
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  postgres_data:

⚙️ 3. 애플리케이션 설정 파일

# config.yml
app:
  name: "나의 멋진 앱"
  version: "1.0.0"
  debug: false

database:
  host: localhost
  port: 5432
  name: myapp_db
  user: app_user
  password: secret123

# 로깅 설정
logging:
  level: INFO
  file: /var/log/app.log
  max_size: 10MB
  backup_count: 5

# 외부 API 설정
apis:
  weather:
    url: "https://api.weather.com"
    key: "your-api-key"
    timeout: 30
  
  payment:
    url: "https://api.payment.com"
    key: "payment-key"
    retry_count: 3

# 기능 플래그
features:
  new_ui: true
  beta_features: false
  analytics: true

# 알림 설정
notifications:
  email:
    enabled: true
    smtp_server: smtp.gmail.com
    port: 587
  
  slack:
    enabled: false
    webhook_url: ""

🚀 4. Kubernetes 배포 설정

# deployment.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  labels:
    app: my-app

spec:
  replicas: 3  # 3개의 인스턴스 실행
  
  selector:
    matchLabels:
      app: my-app
  
  template:
    metadata:
      labels:
        app: my-app
    
    spec:
      containers:
        - name: app-container
          image: my-app:latest
          ports:
            - containerPort: 8080
          
          # 환경 변수
          env:
            - name: DATABASE_URL
              value: "postgresql://..."
            - name: REDIS_URL
              value: "redis://..."
          
          # 리소스 제한
          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "512Mi"
              cpu: "500m"

---
# service.yml
apiVersion: v1
kind: Service
metadata:
  name: my-app-service

spec:
  selector:
    app: my-app
  
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  
  type: LoadBalancer

🎨 YAML 스타일 가이드

✅ 좋은 YAML 작성법

# 1. 일관된 들여쓰기 (2칸 권장)
database:
  host: localhost
  port: 5432

# 2. 의미 있는 키 이름
user_settings:
  notification_enabled: true
  theme: dark

# 3. 문자열에 따옴표 사용 (특수문자 포함 시)
message: "Hello, World!"
email: "[email protected]"

# 4. 긴 리스트는 여러 줄로
allowed_hosts:
  - localhost
  - 127.0.0.1
  - example.com
  - "*.mydomain.com"

# 5. 복잡한 구조는 주석으로 설명
# 데이터베이스 연결 설정
database:
  # 기본 연결 정보
  connection:
    host: localhost
    port: 5432
  
  # 연결 풀 설정
  pool:
    min_size: 5
    max_size: 20

❌ 피해야 할 YAML 패턴

# 1. 탭과 스페이스 혼용 (안 됨!)
database:
	host: localhost  # 탭 사용
  port: 5432       # 스페이스 사용

# 2. 들여쓰기 불일치
users:
  - name: John
    age: 30
     email: [email protected]  # 들여쓰기 틀림

# 3. 콜론 뒤 공백 없음
name:John  # 틀림
age :30    # 콜론 앞 공백도 틀림

# 4. 특수 문자를 따옴표 없이 사용
password: p@ssw0rd!  # 특수문자는 따옴표로 감싸기
url: "https://example.com"  # URL도 따옴표 권장

🔧 YAML 검증 및 디버깅

온라인 YAML 검증 도구

  1. yamllint.com - YAML 문법 검사
  2. jsonformatter.org/yaml-validator - YAML 유효성 검증
  3. codebeautify.org/yaml-validator - YAML 포맷 확인

VS Code에서 YAML 작업

// settings.json
{
  "yaml.validate": true,
  "yaml.hover": true,
  "yaml.completion": true,
  "[yaml]": {
    "editor.insertSpaces": true,
    "editor.tabSize": 2,
    "editor.autoIndent": "advanced"
  }
}

일반적인 YAML 오류들

# 오류 1: 들여쓰기 문제
database:
 host: localhost     # 1칸 들여쓰기
  port: 5432         # 2칸 들여쓰기 (불일치!)

# 수정
database:
  host: localhost    # 2칸 들여쓰기
  port: 5432         # 2칸 들여쓰기

# 오류 2: 따옴표 문제
message: It's a beautiful day  # 어포스트로피 문제

# 수정
message: "It's a beautiful day"

# 오류 3: 특수 값 처리
version: 1.0    # 숫자로 인식됨
enabled: yes    # 불린으로 인식됨

# 수정 (문자열로 처리하려면)
version: "1.0"
enabled: "yes"

💡 YAML 활용 팁

1. 멀티라인 문자열

# | : 줄바꿈 유지
description: |
  이것은 여러 줄에 걸친
  긴 설명문입니다.
  줄바꿈이 그대로 유지됩니다.

# > : 줄바꿈을 공백으로 변환
summary: >
  이것은 긴 문장이지만
  하나의 줄로 합쳐집니다.
  공백으로 연결됩니다.

2. 앵커와 별칭 (재사용)

# 앵커 정의 (&)
default_config: &default
  timeout: 30
  retry: 3

# 별칭 사용 (*)
development:
  <<: *default  # default_config 내용 상속
  debug: true

production:
  <<: *default  # default_config 내용 상속
  debug: false

3. 환경 변수 사용 패턴

# Docker Compose에서 환경 변수
database:
  host: ${DB_HOST:-localhost}     # 기본값 설정
  port: ${DB_PORT}               # 환경 변수 필수
  password: ${DB_PASSWORD:?error} # 없으면 에러

이제 YAML을 자신있게 사용할 수 있을 거예요! 🎉