1

I have an ansible custom module, that have a configuration file in YAML format. Now the question is how should I load that YAML file inside the module?

NOTE as I understand I can't simply use something like PyYAML since ansible will run my module on the node that it is configuring and maybe that system does not have PyYAML installed.

NOTE Also ansible itself have ansible.parsing.utils.yaml.from_yaml it is not usable by the modules.

So funny as it may sound, I don't know how to load a YAML file in custom ansible module. Please help

1 Answers1

0

It's a great question. It does sound funny and you'd expect a simple answer but as far as i can see these are the facts.

The latest development branch of ansible has /lib/ansible/module_utils/common/yaml.py which can be used by modules because it is under module_utils. see here

If you look at the source code all it's doing is import yaml as _yaml, which you could do yourself inside your custom module. My understanding is this is using PyYAML, which is documented here. (someone correct me if I"m wrong! I don't fully understand the comment in that file stating "preferring the YAML compiled C extensions...")

Anyway, if your target machine does not have PyYAML you can always add a task to ensure its there. e.g.

- name: Install PyYAML python package
  pip:
    name: pyyaml

and then use it in your own module with:

from yaml import load, dump
try:
    from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
    from yaml import Loader, Dumper

# ...

data = load(stream, Loader=Loader)

# ...

output = dump(data, Dumper=Dumper)
Adam Griffiths
  • 1,602
  • 1
  • 13
  • 17