tl;dr
import ast
desired_dict = ast.literal_eval(module.params['json_str'])
let's do it.
When writing an Ansible playbook, In many cases, a JSON file is read and passed as a character string.
tasks:
- name: Update
spam_module:
state: present
json_str: "{{ lookup('file', 'ham.json') }}"
To read this in the module
argument_spec.update(
dict(
json_str=dict(type='str', required=True),
state=dict(default='present', type='str', choices=['present', 'absent']),
)
)
module = AnsibleModule(argument_spec=argument_spec)
print(module.params['json_str'])
I can read it by doing something like
Double quotes are converted to single quotes in module.params
.
At this time, trying to convert to JSON easily fails.
desire_dict = json.loads(module.params['json_str'])
# Fail!!!
Since the character string enclosed in single quotes can be handled as Abstract Syntax Tree in Python,
desired_dict = ast.literal_eval(module.params['json_str'])
It's a good idea to convert it to a dictionary using ʻast.literal_eval`.
I want to compare two JSONs for idempotency check I dropped it in a dictionary and compared it.
However, JSON does not guarantee the order of lists, but dictionaries do guarantee the order, so it is not a strict comparison. Something like that is common in Ansible, so let's do our best.
Recommended Posts