【问题标题】:Ansible json key outputAnsible json 密钥输出
【发布时间】:2020-04-19 02:14:00
【问题描述】:

我正在使用 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? 我试过这个:

  • 调试:msg={{ output.instance | json_query('hw_eth0{}.ipaddresses') }}

但出现错误

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

【问题讨论】:

  • 是否正确 "hw_datastores": [ "V1", ], ?
  • @SaeidBabaei 不,我删除了真正的,为什么?

标签: json ansible ansible-2.x


【解决方案1】:

你的 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 值转换为空字符串。

从名字来看,我猜这个参数应该在不为空的时候返回一个列表。如果您需要在剧本中检查这一点,最佳做法是验证参数长度,例如:

- 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多