21

我是 ansible 的新手,我在从 ansible 角色的 json 文件中读取值时遇到问题。我的变量具有如下值:

{
  "queue": {
    "first": {
      "car": "bmw",
      "year": "1990",
      "model": "x3",
      "color": "blue"
    },
    "second": {
      "car": "bmw",
      "year": "2000",
      "model": "318",
      "color": "red"
    }
  }
}

我试图打印颜色的值只是为了将它与其他一些变量进行比较。我曾经with_dict迭代 json 对象(存储在名为 jsonVar 的变量中),如下所示:

- name: test loop
  with_dict: "{{jsonVar}}"
  shell:  |
        if echo "blue" | grep -q "${{item.value.color}}" ; then
           echo "success"

到目前为止,从 if 语句中获取颜色值从 json 到“蓝色”的比较还没有运气。我想知道我是否做错了什么?提前致谢!

4

3 回答 3

20

您可以使用名为的查找插件读取 json 文件file并将其传递给from_jsonjinja2 过滤器。with_dict您在循环中也有错误,因为您必须遍历jsonVar['queue'],而不仅仅是jsonVar. 这是一个有效的完整代码:

---
- hosts: your_host
  vars:
    jsonVar: "{{ lookup('file', 'var.json') | from_json }}"
  tasks:
    - name: test loop
      with_dict: "{{ jsonVar['queue'] }}"
      shell: |
        if echo "blue" | grep -q "{{ item.value.color }}" ; then
            echo "success"
        fi
于 2016-04-19T21:52:30.830 回答
11

您可以使用 | json_query 过滤器。

http://docs.ansible.com/ansible/playbooks_filters.html#json-query-filter

但请确保您输入的文件格式也正确,如果不是,则可以使用两个过滤器,第一个转换为适当的过滤器,第二个执行 json 查询。

前任:-{{ variable_name | from_json | json_query('')}}

在你的情况下,我认为这会有所帮助:

tasks: print the color
set_fact:
  color1 : "{{ jsonVar | from_json | json_query('queue.[0].['color']')}}"
  color2 : "{{ jsonVar | from_json | json_query('queue.[1].['color']')}}"

但请注意 Ansible 版本等要求

于 2017-03-30T10:53:27.963 回答
2

2020 年的答案,因为我只需要弄清楚。假设文件名为 vars.json 并且与您的 yml 位于同一目录中。

---
- hosts: all
  gather_facts: no
  vars:
    position: second
    field: year
  tasks:
  - name: Include Site Vars
    include_vars: vars.json

  - name: Debug JSON Vars
    debug:
      msg: "{{ queue[position][field] }}"
于 2020-08-13T00:07:53.247 回答