Python (Scripting) - Remove keys from a YAML file using ruamel.yaml
by
Jeremy Canfield |
Updated: January 31 2024
| Python (Scripting) articles
Let's say you have a file named domains.yml that contains the following.
domains:
foo.example.com:
alias: "foo"
region: "us-east-1"
bar.example.com:
alias: "bar"
region: "us-east-1"
And you want to modify the file, removing the bar.example.com key and it's child keys and values. This can be done using ruamel.yaml. The pip install command can be used to install the ruamel.yaml package.
pip install ruamel.yaml
And here is how you could create a new file, removing the bar.example.com key and it's child keys and values.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/original.yml, "r") as original_file:
dictionary = yaml.load(open("/path/to/)
del dictionary['domains']['foo.example.com']
with open("/path/to/new.yml", "w") as new_file:
yaml.dump(dictionary, new_file)
Let's say line 1 of the YAML file contains three dashes, which is fairly common with Ansible playbooks.
---
domains:
foo.example.com:
alias: foo
region: us-east-1
bar.example.com:
alias: bar
region: us-east-1
In this scenario, yaml.explicit_start = True will need to be set to include line 1 in yaml.dump.
#!/usr/bin/python
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
with open("domains.yml", "r") as file:
yaml_dict = yaml.load(file)
del dictionary['domains']['foo.example.com']
with open("/path/to/new.yml", "w") as new_file:
yaml.dump(dictionary, new_file)
Did you find this article helpful?
If so, consider buying me a coffee over at