YAML is a format often used for configuration files, and it is quite common to need to merge several of them.
For example, we might have a configuration shared across several environments, along with specific files for development, testing, or production. Rather than duplicating the entire configuration in each file, it is better to separate common settings from those that vary depending on the environment.
But how do we merge these YAML files? There are several solutions, depending on the programming language used and the desired result.
Why merge multiple YAML files?
Let's go back to the example mentioned in the introduction: an application has a common configuration and a configuration specific to each environment. Here is a config.yaml file:
database:
host: localhost
port: 3306
username: app
password: secret
cache:
enabled: true
ttl: 3600
debug: false
For the development environment, we simply want to change a few settings. So we create a development.yaml file:
database:
host: 127.0.0.1
password: dev
debug: true
The goal is to obtain a final configuration that keeps the common settings while overriding those defined in the environment-specific file:
database:
host: 127.0.0.1
port: 3306
username: app
password: dev
cache:
enabled: true
ttl: 3600
debug: true
This is generally referred to as a deep merge, because simply replacing top-level keys is not enough: nested objects must also be merged.
Merging YAML files with Python
Python does not provide built-in functions for reading and merging YAML files. So we will use the PyYAML library. Let's start by installing it:
pip install pyyaml
We can then load our two files:
import yaml
with open("config.yaml", "r") as file:
config = yaml.safe_load(file)
with open("development.yaml", "r") as file:
development = yaml.safe_load(file)
All that remains is to merge the two dictionaries. Python does not provide a built-in function for performing a deep merge, so we can write a small recursive function:
def deep_merge(base, override):
result = base.copy()
for key, value in override.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
We can now merge the two configurations:
merged = deep_merge(config, development)
print(yaml.dump(merged, sort_keys=False))
This function keeps keys that are only present in the base configuration and replaces values when the same key exists in both files.
This implementation treats lists as simple values. If a list exists in both files, the one from the second file completely replaces the first. You can adapt this behavior depending on your requirements.
Merging YAML files with PHP
PHP does not provide native functions for parsing or generating YAML either. We will use the Symfony YAML library.
Install it with Composer:
composer require symfony/yaml
We can then load our files:
use Symfony\Component\Yaml\Yaml;
$config = Yaml::parseFile('config.yaml');
$development = Yaml::parseFile('development.yaml');
To merge associative arrays, PHP provides the array_replace_recursive() function:
$merged = array_replace_recursive($config, $development);
echo Yaml::dump($merged, 4);
The result is what we are looking for: values from development.yaml replace those from config.yaml, including values in nested arrays.
However, be careful with numeric keys. array_replace_recursive() merges indexed arrays by position rather than always replacing them entirely.
For example:
$base = [
'users' => ['Alice', 'Bob']
];
$override = [
'users' => ['Charlie']
];
$result = array_replace_recursive($base, $override);
The result will be:
[
'users' => ['Charlie', 'Bob']
]
This is not necessarily the desired behavior for a configuration file. If we want to replace lists entirely, we will need to adapt our merge function.
Using YAML anchors and aliases
YAML also provides a built-in mechanism for reusing configuration blocks: anchors and aliases.
Let's take this example:
database: &database
host: localhost
port: 3306
username: app
development:
database:
<<: *database
host: 127.0.0.1
password: dev
production:
database:
<<: *database
host: db.example.com
password: secret
The &database anchor defines a reusable block. The *database alias allows us to reuse it elsewhere. The << operator merges the keys from the referenced block into another mapping. Values explicitly defined in the current block take precedence.
This approach is particularly useful for avoiding repeated configurations within a single YAML file.
However, keep in mind that anchors and aliases cannot be used to directly merge several independent files. They are intended to reuse blocks within a YAML document.
What should we do with lists?
We have seen that merging nested objects is relatively straightforward. With lists, however, things are a little more complicated, and we need to think about what we actually want.
Imagine these two configurations:
config.yaml file:
extensions:
- cache
- logger
- database
development.yaml file:
extensions:
- debug
What result do we want?
There are two possible behaviors:
Replace the list:
extensions:
- debug
Concatenate the lists:
extensions:
- cache
- logger
- database
- debug
Unfortunately, there is no universal rule. In an application configuration, completely replacing a list is often more predictable. In other situations, particularly when adding extensions or plugins, concatenating the lists may be more useful.
It is therefore better to explicitly define the expected behavior rather than letting a library decide for us.
Conclusion
Merging several YAML files is fairly straightforward, provided we define the merge rules properly, especially when it comes to lists.
Well, I'm going back to my configuration files... Docker, Kubernetes, CI/CD, there is always a YAML file lying around somewhere, waiting for someone to take care of it!
YAML merger tool that lets you merge several YAML files directly in your browser