Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

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

Playbook:

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

- name: debug fact
  debug:
    msg: "{{ dataresult.data.start_time_string }}"

output :

TASK [backup_api : debug stdout] 
***********************************************
task path: /home/ansible/cm-dha/roles/backup_api/tasks/main.yml:36
ok: [127.0.0.1] => {
   "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
   }

}

error:

fatal: [127.0.0.1]: 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' The error appears to have been in '/home/ansible/cm-dha/roles/backup_api/tasks/main.yml': line 48, column 5, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: - name: debug fact ^ here "

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

- name: debug fact
  debug:
    msg: "{{ dataresult.data[0].start_time_string }}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...