C.W.K.
Stream
Lesson 06 of 08 · published

Anchor & alias — DRY YAML

~12 min · yaml, anchors, aliases, merge-keys

Level 0평문
0 XP0/64 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete

&anchor 로 한 번 정의, *alias 로 재사용

YAML 이 anchor 지원 — 노드에 &name 으로 이름; alias — 나중에 *name 으로 참조. 파싱된 결과가 같은 노드 값 재사용 (또는 두 사본, 파서의 deep-copy 정책에 따라).

Merge key (<<:)

Merge key 는 YAML 1.1 확장: <<: *base 가 anchored 맵의 모든 키를 현재 맵에 병합, 현재 맵 키가 override. docker-compose 와 CI config 가 중복 없이 base config 공유하는 방식.

주의: merge key 는 YAML 1.2 spec 에 없음, 단 PyYAML, ruamel, js-yaml, 대부분 작동 도구가 여전히 지원. '거의 어디서나 작동; 의존 전 파서 확인' 으로 다뤄.

언제 anchor 잡나

둘 이상 노드가 sync 유지돼야 할 때. anchor 없으면 업데이트 두 곳; anchor 있으면 한 source of truth. 비용은 읽기 시 indirection 한 layer — 반복 있으면 그 가치.

원칙: anchor 와 alias 는 YAML 의 변수 등가물. 반복되는 config 를 유지보수 가능하게 만듦. 과용하면 파일 읽기 어려움; 사용 부족이면 같은 env-var block 사본 세 개 유지. '세 번 이상 사용 = anchor 화' 목표.

Code

반복 값에 anchor + alias·yaml
default_timeout: &timeout 30

endpoints:
  - name: search
    timeout: *timeout
  - name: index
    timeout: *timeout
  - name: admin
    timeout: *timeout
공유 base config 에 merge key·yaml
base_service: &base
  image: ghcr.io/cwk/api:1.0
  restart: unless-stopped
  environment:
    LOG_LEVEL: info

services:
  api:
    <<: *base
    ports: ["8000:8000"]
  worker:
    <<: *base
    command: ["python", "worker.py"]
  admin:
    <<: *base
    ports: ["8001:8001"]
    environment:
      LOG_LEVEL: debug   # base override
리스트 요소에 anchor·yaml
shared_env: &shared_env
  - name: TZ
    value: Asia/Seoul
  - name: LOG_LEVEL
    value: info

containers:
  - name: api
    env: *shared_env
  - name: worker
    env: *shared_env

External links

Exercise

겹치는 config 가진 여러 service 가 있는 docker-compose.yaml 골라. 공유 부분을 <<: *base 의 anchor 로 추출. docker compose config 실행해서 파싱된 출력이 변하지 않은 거 확인. 내재화: anchor 가 YAML 의 리팩토링.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.