在ansible中使用json_query组合属性值

2024-01-14

我想使用 ansible 中的 json_query 将两个属性组合成由分隔符分隔的单个字符串
样本数据

{
  "locations": [
    {"name": "Seattle", "state": "WA"},
    {"name": "New York", "state": "NY"},
    {"name": "Bellevue", "state": "WA"},
    {"name": "Olympia", "state": "WA"}
  ]
}

如上面的数据集所示,我试图过滤状态“WA”,执行的输出是:

[
    "Seattle-WA",
    "Bellevue-WA",
    "Olympia-WA"
]

到目前为止我已经尝试过的:

    - debug:
        msg: "{{ chart_list.HELM_CHARTS | json_query(\"[?state == 'WA'].{name:name,state:state}\") }}"
Output:
[
  {
    "name": "Seattle",
    "state": "WA"
  },
  {
    "name": "Bellevue",
    "state": "WA"
  },
  {
    "name": "Olympia",
    "state": "WA"
  }
]

更新 :我通过反复试验的方法得到了预期的结果,这些是我的发现:

[?state == 'WA'].[join('-',[name,state])][]
Output:
[
  "Seattle-WA",
  "Bellevue-WA",
  "Olympia-WA"
]

另外,如果您提供的输入是 unicode 格式,我建议您添加to_json | from_json表达式如下:

        selected_cities: "{{ test.locations| to_json | from_json | json_query(\"[?state == 'WA'].[join('-',[name,state])][]\") }}"

使用上述表达式将消除使用值或在任何条件下的 unicode 错误。 查看JMESPath https://jmespath.org/有关 json_query 的更多详细信息,它对于解决问题确实很有帮助。


例如

    - debug:
        msg: "{{ locations|
                 json_query('[?state == `WA`].[name,state]')|
                 map('join', '-')|list }}"

gives

  msg:
  - Seattle-WA
  - Bellevue-WA
  - Olympia-WA

仅使用 Jinja2 过滤器给出以下任务的结果相同

    - debug:
        msg: "{{ _names|zip(_states)|map('join', '-')|list }}"
      vars:
        _locations: "{{ locations|selectattr('state', 'eq', 'WA')|list }}"
        _names: "{{ _locations|map(attribute='name')|list }}"
        _states: "{{ _locations|map(attribute='state')|list }}"

json_query 问题(在2.10及更高版本中修复)

有JMES路径join https://jmespath.readthedocs.io/en/latest/specification.html#join。很遗憾

    - debug:
        msg: "{{ locations|
                 json_query('[].join(`-`, [name,state])') }}"

fails

消息:|- json_query 过滤器插件中的 JMESPathError: 在函数 join() 中,值的类型无效:Seattle,预期为以下之一:['array-string'],收到:“AnsibleUnicode”

to_json|from_json 解决方法

引用自json_query:添加starts_with 和 contains 的示例 #72821 https://github.com/ansible/ansible/pull/72821

从寄存器变量返回的数据结构需要使用 to_json | 进行解析from_json 以获得正确的结果。修复:ansible-collections/community.general#320 https://github.com/ansible-collections/community.general/issues/320

    - debug:
        msg: "{{ locations|to_json|from_json|
                 json_query('[].join(`-`, [name,state])') }}"

gives

  msg:
  - Seattle-WA
  - New York-NY
  - Bellevue-WA
  - Olympia-WA
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在ansible中使用json_query组合属性值 的相关文章

随机推荐