Files
iac-opentofu-public/merge_yaml.py
2025-10-21 19:25:08 +00:00

46 lines
1.1 KiB
Python

#!/usr/bin/env python3
from ruamel.yaml import YAML
import sys
import json
from collections.abc import Mapping
def deep_merge_yaml(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result:
if isinstance(result[key], list) and isinstance(value, list):
result[key] = result[key] + value
elif isinstance(result[key], Mapping) and isinstance(value, Mapping):
result[key] = deep_merge_yaml(result[key], value)
else:
result[key] = value
else:
result[key] = value
return result
def main():
input_data = json.load(sys.stdin)
file1 = input_data["file1"]
file2 = input_data["file2"]
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
with open(file1, "r") as f1, open(file2, "r") as f2:
yaml1 = yaml.load(f1)
yaml2 = yaml.load(f2)
merged = deep_merge_yaml(yaml1, yaml2)
from io import StringIO
output = StringIO()
yaml.dump(merged, output)
print(json.dumps({
"merged_yaml": output.getvalue()
}))
if __name__ == "__main__":
main()