I have a some.yaml
file with the below contents.
init_config: {}
instances:
- host: <IP>
username: <username>
password: <password>
The yaml file should be parsed and updated as below.
init_config: {}
instances:
- host: 1.2.3.4
username: Username
password: Password
How do I parse the values and update them appropriately?
I don't know if you need YAML. Aside from using the YAML tag, it seems that you have no interest in the YAML document. So why not using Jinja2 or some template language?
I don't know if it is a good idea, but if you only need to obtain a file with some fields changed, you don't need to actually parse the YAML document and can benefit from a Template language directly.
Bonus: Use case
I have worked with very complex YAML documents, for which there are tags unknown
Performing a valid parse of this document is difficult and time-consuming. I only need to populate some values, and the YAML is sent to a third-party application. So instead of parsing the YAML or trying to generate a valid document directly using pyyaml, is simpler (more time-efficient, less bug-prone) to generate it directly through templates. Moreover, template languages can easily be used with loops to populate dynamically sized fields.
The ruamel.yaml package was specifically enhanced (by me starting from PyYAML) to do this kind of round-trip, programmatic, updating.
If you start with (please note I removed the extra initial spaces):
and run:
The output will be:
The ordering of mapping keys (
host
,username
andpassword
), the style and the comments are preserved without any further specific action.Instead of having the indent and block sequence indent guessed, you can do a manual traditional load, and set the indent values yourself:
If you look at the history of this answer, you can see how to do this with a more limited, PyYAML like, API.
Here's how i generate docker-crane templates for dev, production, stage, etc...
--- crane_gen.py ---
5. python crane_gen.py > result.yaml
Answer inspired by @MariusSiuram
This is how i can read from the above file i mentioned, parse and update as needed.
Here are sample using
PyYaml
. As I understand you have something like template inyaml
format, and you have to substitute places in angle brackets with actual values.