小编典典

从json输出中提取变量,然后使用ansible调试并注册outout

json

嗨,我有一个问题,是在进行curl解析并注册回ansible后,要从json输出中提取变量之一

剧本:

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

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

输出:

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
   }

}

错误:

致命的:[127.0.0.1]:失败!=> {“ failed”:true,“
msg”:“字段’args’的值无效,该值似乎包含未定义的变量。错误是:’dict object’没有属性’data’\ n \ n错误似乎出在“
/home/ansible/cm-
dha/roles/backup_api/tasks/main.yml”中:第48行第5列,但具体位置可能取决于文件中的语法问题。 \ n \
n出现问题的行似乎是:\ n \ n \ n-名称:调试事实\ n ^这里\ n“

尝试提取值start_time_string时发生错误

所以如何做可能是因为我尝试了很多事情,例如使用with_items,with_dict,模拟data []输出进行调试,甚至进行json查询,但都没有成功

所以这里有什么帮助吗?


阅读 721

收藏
2020-07-27

共1个答案

小编典典

不要使用debug分配事实,set_fact而是使用:

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

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