YAML Anchors and Aliases
Understand YAML anchors and aliases, how they reference reusable values, how merge keys work and when these features are useful in configuration files.
YAML anchors and aliases provide a way to define a value once and reuse it in multiple locations within the same YAML document. They are particularly useful in configuration files where the same settings, objects or sequences would otherwise have to be repeated. By referencing an existing value, YAML can reduce duplication and make certain configuration structures easier to maintain.
Anchors and aliases are part of YAML's native syntax rather than features provided by a particular application. An anchor assigns a name to a node, while an alias references that previously defined node. YAML also supports merge functionality in commonly used YAML implementations, allowing mappings to inherit values from anchored mappings.
What Is a YAML Anchor?
A YAML anchor assigns a reusable name to a node. The ampersand character (&) introduces an anchor, followed by the anchor name. The anchored value can then be referenced later using an alias.
defaults: &defaults
timeout: 30
retries: 3In this example, the mapping containing timeout and retries is assigned the anchor named defaults. The anchor does not create a separate YAML property by itself. It gives the node a reusable identifier that another part of the document can reference.
What Is a YAML Alias?
A YAML alias references a node that has previously been assigned an anchor. The asterisk character (*) introduces an alias. Instead of writing the original value again, the alias points to the anchored value.
defaults: &defaults
timeout: 30
retries: 3
production: *defaultsHere, production uses the alias *defaults, so it refers to the mapping defined by the defaults anchor. This allows the same structure to be reused without duplicating its contents.
Anchor and Alias Syntax
| Syntax | Purpose |
|---|---|
| &name | Defines an anchor named name |
| *name | References an existing anchor |
| <<: *name | Merges an anchored mapping in implementations supporting merge keys |
A Simple Example
The simplest use case is defining a shared configuration object and reusing it in another mapping.
base: &base
host: example.com
port: 443
server: *baseThe server value references the same anchored mapping. This is useful when multiple parts of a configuration need to use an identical structure.
Why Use Anchors and Aliases?
The main benefit of anchors and aliases is reducing repetition. Repeated configuration values increase maintenance work because changing one shared setting may require updating multiple copies. An anchor allows the shared value to be declared once and reused.
- Reduce duplicated configuration.
- Reuse common mappings and sequences.
- Keep related configuration values consistent.
- Make large configuration files more compact.
- Simplify certain repeated environment settings.
Anchoring a Mapping
Mappings are one of the most common structures used with anchors. A mapping can contain several related properties and then be referenced elsewhere using an alias.
database: &database
host: db.example.com
port: 5432
ssl: true
primary: *database
backup: *databaseBoth primary and backup reference the anchored database mapping. This can be useful when several configuration sections initially share the same settings.
Anchoring a Sequence
Anchors can also be assigned to sequences. This allows a list to be reused in another location without repeating every item.
ports: &ports
- 80
- 443
web_ports: *portsThe web_ports value references the same sequence defined by the ports anchor. This can be convenient for lists that occur in multiple configuration sections.
Anchoring Scalar Values
Anchors are not limited to mappings and sequences. Scalar values such as strings, numbers and booleans can also be anchored and referenced.
environment: &environment production
current_environment: *environmentAlthough anchoring a single scalar can be useful in some configurations, it may provide little benefit when the value is short and used only a few times. Anchors are generally most valuable when they eliminate substantial duplication or represent an intentionally shared configuration value.
Merge Keys
YAML configurations often use anchors together with the merge key syntax to create a base mapping and then extend it with additional properties. The common syntax is <<: followed by an alias.
defaults: &defaults
timeout: 30
retries: 3
logging: true
production:
<<: *defaults
retries: 5The production mapping inherits the values from defaults and overrides retries with a value of 5. This pattern can make environment-specific configuration more concise because shared settings remain in one base mapping.
Overriding Merged Values
One of the most useful patterns with merged mappings is defining common defaults and overriding only the properties that differ. This separates shared configuration from environment-specific settings.
defaults: &defaults
host: localhost
port: 8080
debug: false
production:
<<: *defaults
host: api.example.com
debug: false
development:
<<: *defaults
debug: trueThe development and production mappings inherit the common defaults while changing only the properties that need different values. This pattern is common in configuration files containing multiple environments.
Multiple Merged Anchors
Some YAML processors support merging multiple anchored mappings. This allows a configuration section to combine several reusable groups of settings.
network: &network
host: example.com
port: 443
logging: &logging
level: info
enabled: true
application:
<<: [*network, *logging]This pattern separates reusable configuration concerns into independent mappings. The application mapping can then combine them instead of repeating network and logging properties.
Anchors Do Not Work Across Documents
Anchors and aliases are normally scoped to a YAML document. An anchor defined in one YAML document cannot simply be referenced from a separate document as though both documents shared the same namespace.
---
defaults: &defaults
timeout: 30
---
server: *defaultsWhen multiple YAML documents are separated by document markers, applications should not assume that anchors can be referenced across those document boundaries. If values need to be shared between separate files, the application or configuration system may need its own mechanism for reuse.
Anchors vs Copying Values
| Approach | Main Characteristic |
|---|---|
| Duplicate values | Simple but increases repetition |
| Anchor and alias | Reuses an existing YAML node |
| Merge mapping | Combines reusable mapping values with overrides |
| External configuration | Shares values through an application-specific mechanism |
Anchors are particularly useful when the repeated data belongs to the same YAML document and should remain logically connected. If configuration must be shared across independent files or generated dynamically, an external configuration mechanism may be easier to maintain.
Anchors and Object References
YAML parsers may represent aliases as references to the same underlying node rather than simply treating them as duplicated text. This distinction matters when applications load YAML into in-memory objects and later modify those structures.
The exact behavior depends on the parser and the programming language. Some libraries preserve alias relationships, while others may resolve them into ordinary values. Applications that modify parsed YAML structures should therefore consult the documentation of their specific YAML library.
Recursive References
YAML aliases can represent recursive structures because an alias can refer to an anchored node that eventually contains a reference back to itself. This is a powerful feature, but it is rarely necessary for ordinary application configuration.
node: &node
name: root
child: *nodeThis example creates a self-referential structure. A parser must correctly handle such references, and applications need to be careful when traversing or serializing recursive data because naive recursive algorithms can enter an infinite loop.
Anchors and YAML Security
Anchors themselves are not a security mechanism. However, YAML parsers need to handle aliases carefully because deeply nested or highly repetitive structures can consume significant processing resources. Applications processing untrusted YAML should use a parser configuration appropriate for untrusted input and consider resource limits.
The security implications depend heavily on the parser and the features it enables. In particular, applications should distinguish ordinary data parsing from unsafe features that may construct language-specific objects or execute application-defined behavior.
Common Use Cases
- Shared application defaults.
- Reusable environment configuration.
- Common service settings.
- Repeated deployment parameters.
- Shared lists of ports or permissions.
- Configuration templates within one YAML document.
Using Anchors in Configuration Files
A practical configuration pattern is to define a base section near the beginning of the document and then reference or merge it later. This makes the relationship between defaults and environment-specific values explicit.
service_defaults: &service_defaults
restart: always
timeout: 30
logging: true
service_a:
<<: *service_defaults
timeout: 60
service_b:
<<: *service_defaultsThis structure keeps shared service settings in one place while allowing individual services to override selected properties. It can be much easier to maintain than copying the same configuration into every service definition.
When Not to Use Anchors
Anchors are not automatically the best solution for every repeated value. A configuration can become harder to understand if many anchors are scattered throughout the document or if aliases are used for values that would be clearer when written directly.
- Avoid anchors when the repeated value is trivial and used only twice.
- Avoid excessive nesting of aliases.
- Avoid complex anchor structures that obscure the actual configuration.
- Avoid relying on merge behavior without confirming parser support.
- Avoid recursive aliases unless they are genuinely required.
Readability Considerations
Reducing duplication does not always make a configuration easier to read. A new developer can understand an explicit mapping immediately, while an alias may require searching elsewhere in the file to discover its contents. Good YAML design balances reuse with clarity.
Anchors in Different YAML Tools
Support for anchors and aliases is common among mature YAML parsers, but behavior can vary around merge keys, recursive references, serialization and advanced YAML features. A document that parses correctly in one tool should still be tested with the parser used by the target application.
| Feature | Compatibility Consideration |
|---|---|
| Basic anchors | Widely supported by YAML parsers |
| Basic aliases | Widely supported |
| Merge keys | Verify parser and YAML version behavior |
| Recursive aliases | Verify parser and application behavior |
| Serialization | Check whether alias relationships are preserved |
Debugging Anchor Problems
When an anchor or alias causes a parsing error, first check that the anchor is defined before the alias is used, that the names match exactly and that indentation is correct. If merge syntax is involved, verify that the parser supports the syntax and that the merged value is a mapping.
- Check the anchor name for spelling differences.
- Make sure the anchor is defined before its alias.
- Verify YAML indentation.
- Confirm that merge syntax is supported.
- Check whether the referenced node has the expected type.
- Validate the complete YAML document with the target parser.
Best Practices
- Use anchors to eliminate meaningful duplication.
- Give anchors descriptive names.
- Keep reusable defaults together when practical.
- Use aliases for clearly shared values.
- Use merge mappings when supported and appropriate.
- Keep anchor structures simple enough to understand.
- Test YAML with the parser used by the target application.
- Avoid unnecessary recursive references.
- Validate configuration before deployment.
- Document unusual anchor patterns when they are not immediately obvious.
Common Mistakes
- Using an alias before defining its anchor.
- Misspelling an anchor name.
- Assuming anchors work across separate YAML documents.
- Assuming every parser supports merge keys identically.
- Using aliases so extensively that the configuration becomes difficult to follow.
- Creating recursive references without considering parser behavior.
- Assuming aliases are always expanded into independent copies.
- Ignoring parser-specific behavior when processing untrusted YAML.
Frequently Asked Questions
What is a YAML anchor?
A YAML anchor assigns a reusable name to a YAML node. The ampersand character introduces the anchor, and the anchored value can later be referenced using an alias.
What is a YAML alias?
A YAML alias references a node that was previously assigned an anchor. It is introduced with an asterisk and allows the anchored value to be reused without repeating its contents.
What is the difference between an anchor and an alias?
An anchor defines a reusable node, while an alias references that previously defined node. Anchors use the & syntax and aliases use the * syntax.
Can YAML anchors reduce duplication?
Yes. Anchors allow mappings, sequences and scalar values to be defined once and referenced in other locations within the same YAML document.
What is the YAML merge key?
The merge syntax commonly written as <<: *name can incorporate values from an anchored mapping into another mapping, allowing shared defaults to be combined with local overrides when supported by the parser.
Can a YAML alias override an anchor?
An alias references the anchored node rather than overriding it. When merge mappings are used, the receiving mapping can define its own values to override inherited properties according to the parser's merge behavior.
Can YAML anchors be used with arrays?
Yes. YAML sequences can be assigned anchors and referenced using aliases, allowing a list to be reused in another part of the document.
Can YAML anchors be used with strings?
Yes. Scalar values such as strings, numbers and booleans can be anchored, although using anchors for very small values may provide little readability benefit.
Do YAML anchors work across files?
Normally no. Anchors and aliases are scoped to a YAML document. Sharing values between separate files generally requires an application-specific configuration mechanism.
Helpful YAML Tools
A YAML Formatter helps format YAML consistently and makes anchor-based structures easier to inspect, a YAML Tree Viewer provides a structured view of mappings, sequences and referenced values, a YAML Validator checks YAML syntax and helps identify malformed anchor or alias references, a YAML Merge Tool can help combine YAML configuration structures, and a YAML Split Tool can divide YAML documents into smaller parts when working with large configuration files.
Conclusion
YAML anchors and aliases provide a practical way to reuse values and reduce duplication within YAML documents. Anchors define reusable nodes, aliases reference those nodes, and merge mappings can be used to build configurations from shared defaults when supported by the parser. These features are especially useful for repeated configuration structures, environment-specific settings and common service definitions. However, excessive use can reduce readability, and advanced behavior such as merge keys and recursive references may vary between YAML implementations. The best approach is to use anchors where they provide a clear maintenance benefit, keep the structure understandable and always test the resulting YAML with the parser that will process it.