yousef yousef - 5 months ago 76
JSON Question

extracting a variable from json output then debug and register the outout with ansible

Hi I have a problem of getting one of the variables extracted from a json output after doing a curl to be parsed and registered back to ansible


- name: debug stdout
msg: "{{ result.stdout | from_json }}"
register: dataresult

- name: debug fact
msg: "{{ }}"

output :

TASK [backup_api : debug stdout]
task path: /home/ansible/cm-dha/roles/backup_api/tasks/main.yml:36
ok: [] => {
"msg": {
"data": [
"backup_id": 40362,
"certified": null,
"instance_id": 148,
"start_time": 1506985211,
"start_time_string": "10/03/2017 03:00:11 am"
"timestamp": 1507022232



fatal: []: FAILED! => {
"failed": true,
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'data'\n\nThe error appears to have been in '/home/ansible/cm-dha/roles/backup_api/tasks/main.yml': line 48, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: debug fact\n ^ here\n"

The error is happening when trying to extract the value start_time_string

so how to do it probably as I tried too many things like using with_items, with_dict , simulating the data[] output to debug and even doing a json query but without success

so any help here?

Answer Source

Don't use debug to assign facts, use set_fact instead:

- name: debug stdout
    dataresult: "{{ result.stdout | from_json }}"

- name: debug fact
    msg: "{{[0].start_time_string }}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download