Bootstrap FreeKB - Python (Scripting) - Read YAML file using ruamel.yaml
Python (Scripting) - Read YAML file using ruamel.yaml

Updated:   |  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

 

open can be used to open a file for reading or writing. The second parameter can be:

In this example, the domains.yml file will be opened for reading.

#!/usr/bin/python

filename = "/tmp/domains.yml"

file = open(filename, "r")
print(file.read())
file.close()

 

Which should return something like this.

~]$ python3 testing.py 
domains:
  foo.example.com:
    alias: foo
    region: us-east-1
  bar.example.com:
    alias: bar
    region: us-east-1

 

ruamel.yaml can be used to parse the YAML. The pip install command can be used to install the ruamel.yaml package.

pip install ruamel.yaml

 

And now you can use ruamel.yaml to parse the YAML. In this example

  • yaml.load is used to load the YAML in a dictionary
  • yaml.dump is used to display the output in YAML format
#!/usr/bin/python
import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()

with open("domains.yml", "r") as file:
  yaml_dict = yaml.load(file)

print(yaml_dict)
yaml.dump(yaml_dict, sys.stdout)

 

Which should return a dictionary like this.

{'domains': {'foo.example.com': {'alias': 'foo', 'region': 'us-east-1'}, 'bar.example.com': {'alias': 'bar', 'region': 'us-east-1'}}}

 

And yaml.dump should return something like this.

domains:
  foo.example.com:
    alias: foo
    region: us-east-1
  bar.example.com:
    alias: bar
    region: us-east-1

 

And then you can use access the dictionary keys and values, perhaps something like this.

#!/usr/bin/python3
import ruamel.yaml as yaml

filename = "/tmp/domains.yml"

file = open(filename, "r")
yaml_dict = yaml.safe_load(file)
print(f"foo.example.com region = {yaml_dict['domains']['foo.example.com']['region']}")
file.close()

 

Which should print the following.

foo.example.com region = us-east-1

 

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)

yaml.dump(yaml_dict, sys.stdout)

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 250924 in the box below so that we can be sure you are a human.