Anchors and Aliases in YAML are powerful reuse mechanisms that can avoid defining the same content repeatedly, improving configuration file maintainability.
Basic Concepts of Anchors and Aliases
Anchor
- Use
&symbol to define an anchor - Create a reference identifier for a value or structure
- Can reference this anchor elsewhere in the document
Alias
- Use
*symbol to reference an anchor - Points to a previously defined anchor
- Copies the anchor's content when referenced
Basic Syntax
yaml# Define anchor defaults: &default_config timeout: 30 retry: 3 log_level: info # Use alias to reference service1: <<: *default_config name: service1 port: 8000 service2: <<: *default_config name: service2 port: 8001
Use Cases
1. Reusing Configuration Values
yaml# Define common configuration database: &db_config host: db.example.com port: 5432 ssl: true # Reuse in multiple services service_a: database: *db_config name: Service A service_b: database: *db_config name: Service B
2. Merging Maps
Use <<: operator to merge anchor content into current map.
yaml# Define base configuration base: &base_config version: "1.0" environment: production debug: false # Inherit and extend api: <<: *base_config name: API Service port: 8080 worker: <<: *base_config name: Worker Service port: 8081 concurrency: 10
3. Reusing Lists
yaml# Define common tags common_tags: &tags - monitoring - logging - backup # Use in multiple resources server1: name: web-server-1 tags: *tags server2: name: web-server-2 tags: *tags
4. Reusing Complex Structures
yaml# Define complex service configuration service_template: &service health_check: enabled: true path: /health interval: 30s resources: cpu: "500m" memory: "512Mi" replicas: 2 # Create multiple service instances frontend: <<: *service name: frontend image: nginx:latest port: 80 backend: <<: *service name: backend image: node:18 port: 3000 resources: cpu: "1000m" memory: "1Gi"
Advanced Usage
1. Multiple Inheritance
yaml# Define multiple base configurations base1: &config1 timeout: 30 retry: 3 base2: &config2 log_level: debug verbose: true # Merge multiple configurations service: <<: [*config1, *config2] name: combined-service
2. Overriding Inherited Values
yaml# Base configuration defaults: &defaults timeout: 30 retry: 3 log_level: info # Override specific values service: <<: *defaults name: critical-service timeout: 60 # Override default value retry: 5 # Override default value
3. Nested Anchors
yaml# Nested anchor definition database: &db connection: &conn host: localhost port: 5432 pool: min: 5 max: 20 # Reference nested anchor service: database: *db cache: connection: *conn # Reference nested connection config
Practical Application Examples
Kubernetes Configuration Reuse
yamlapiVersion: v1 kind: ConfigMap metadata: name: common-config data: app: &app_config name: myapp version: "1.0.0" environment: production --- apiVersion: apps/v1 kind: Deployment metadata: name: frontend spec: template: spec: containers: - name: frontend env: - name: APP_NAME value: *app_config.name - name: APP_VERSION value: *app_config.version --- apiVersion: apps/v1 kind: Deployment metadata: name: backend spec: template: spec: containers: - name: backend env: - name: APP_NAME value: *app_config.name - name: APP_VERSION value: *app_config.version
Docker Compose Configuration Reuse
yamlversion: '3.8' x-common-variables: &common-env NODE_ENV: production LOG_LEVEL: info API_TIMEOUT: 30000 services: web: image: nginx:latest environment: <<: *common-env SERVICE_NAME: web ports: - "80:80" api: image: node:18 environment: <<: *common-env SERVICE_NAME: api ports: - "3000:3000" worker: image: node:18 environment: <<: *common-env SERVICE_NAME: worker
Important Notes
- Anchor Scope: Anchors must be defined before aliases
- Circular References: Avoid creating circular references, which cause parsing errors
- Readability: Overusing anchors may reduce readability
- Version Compatibility: Some YAML parsers may not support advanced features
Best Practices
- Naming Conventions: Use descriptive anchor names
- Documentation: Add comments to explain complex anchors
- Moderate Use: Only use anchors when truly needed for reuse
- Test Validation: Use YAML validation tools to ensure configuration correctness
- Team Standards: Establish anchor usage standards within the team
Common Errors
yaml# ❌ Error: Undefined anchor service: config: *undefined_anchor # ❌ Error: Circular reference a: &ref b: *ref # ❌ Error: Anchor defined after alias service: config: *config defaults: &config timeout: 30