The python-hcl2
library implements a parser for the HCL syntax, but it doesn't have a serializer, and its API is designed to drop all of the HCL specifics and retain only a basic Python data structure, so it doesn't seem to retain enough information to surgically modify the input without losing details such as comments, ordering of attributes, etc.
At the time I'm writing this, the only HCL implementation that explicitly supports updating existing configuration files in-place is the Go package hclwrite
. It allows callers to load in arbitrary HCL source, surgically modify parts of it, and then re-serialize that updated version with only minor whitespace normalization to the unchanged parts of the input.
In principle it would be possible to port hclwrite
to Python, or to implement a serializer from a dictionary like python-hcl2
returns if you are not concerned with preserving unchanged input, but both of these seem like a significant project.
If you do decide to do it, one part that warrants careful attention is serialization of strings into HCL syntax, because the required escaping isn't exactly the same as any other language. You might wish to refer to the escapeQuotedStringLit
function from hclwrite
to see all of the cases to handle, so you can potentially implement compatible logic in Python.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…