首先,我们需要安装ruamel.yaml。然后,我们可以使用以下代码将字典转储到YAML格式:
import ruamel.yaml
data = {'example': {'key': 'value'}, 'other_example': {'other_key': 'other_value'}}
yaml_str = ruamel.yaml.dump(data, default_flow_style=False)
print(yaml_str)
这将输出以下YAML格式的字符串:
example:
key: value
other_example:
other_key: other_value
然而,当我们在Ansible中使用时,它可能会抱怨“Could not determine a constructor for the tag 'tag:yaml.org,2002:python/dict'”。这是由于缺少参数产生的。
为了解决这个问题,我们可以使用RoundTripDumper
替代SafeDumper
。和使用default_flow_style=False
来避免转储为JSON格式。如下所示:
import ruamel.yaml
class AnsibleSafeDumper(ruamel.yaml.RoundTripDumper):
def ignore_aliases(self, data):
return True
data = {'example': {'key': 'value'}, 'other_example': {'other_key': 'other_value'}}
yaml_str = ruamel.yaml.dump(data, Dumper=AnsibleSafeDumper, default_flow_style=False)
print(yaml_str)
这样就可以避免在Ansible中产生任何问题。