Ansible json 键输出

Ansible json key output

我使用的是 ansible 2.9.2,我有这本剧本:

  register: output

- debug: msg={{ output.instance }}

给出了这个输出:

TASK [debug] ***************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "annotation": "",
        "current_snapshot": null,
        "customvalues": {},
        "guest_consolidation_needed": false,
        "guest_question": null,
        "guest_tools_version": "0",
        "hw_cluster": null,
        "hw_datastores": [
            "V1",
        ],
        "hw_esxi_host": "10.10.101.10",
        "hw_eth0": {
            "addresstype": "assigned",
            "ipaddresses": null,
            "label": "",
            "macaddress": "00:00:00:00:00:51",
            "portgroup_key": null,
            "portgroup_portkey": null,
            "summary": "Vlan1"

如何让输出只给我 "ipaddresses": null? 我试过了:

但出现错误

FAILED! => {"msg": "JMESPathError in json_query filter plugin:\ninvalid token: Parse error at column 7, token \"{\" (LBRACE), for expression:\n\"hw_eth0{}.ipaddresses

你的jmespath表达式有误。你可以check the doc for more details

以下应该有效

- debug:
    msg: "{{ output.instance | json_query('hw_eth0.ipaddresses') }}"

同时,在这种情况下您真的不需要 json_query,您只需要读取散列中的值:

- debug:
    var: output.instance.hw_eth0.ipaddresses

请注意,在输出中,ansible 会自动将 json null 值转换为空字符串。

从名字上看,我猜这个参数应该是return一个不为空的列表。如果你需要在你的剧本中检查它,最好的做法是验证参数长度,例如:

- name: Do something only when there are configured IPs
  debug:
    msg: There is at least one IP configured
  when: output.instance.hw_eth0.ipaddresses | length > 0