Ansible playbook,用于从返回的json数据中获取属性

问题描述 投票:0回答:2

我是Ansible的新手,这是我第一次尝试它。我有一个任务从领事Address终点检索属性nodes。我的游戏看起来如下

- hosts: localhost
  connection: local
  tasks:
    - name: "Get the addresses"
      block:
        - name: 'Fetching addresses from consul.'
          uri:
            url: http://consul-server/v1/catalog/nodes
            status_code: 200
            body_format: json
            return_content: yes
          register: nodes
        - set_fact:
            frontend_ips: "{{ item.Address }}"
          when: item.Node == "*hero_node*"
          loop: "{{ nodes }}"

在这里我试图从领事中获取所有节点然后过滤掉节点名称中包含Addresses的节点的hero_node但是我得到一个例外

fatal: [localhost]: FAILIED! => {}.
MSG: Unexpected failure in finding     the lookup name '{{ nodes }} in the available lookup plugin'

nodes json从终点返回看起来像这样:

[
    {
        "Address": "111.111.11.1",
        "Node": "hero-node-1",
        "Metadata": ...
        ...
    },
    {
         ...
         ...
    }
]

任何帮助将非常感激。

ansible ansible-2.x consul
2个回答
1
投票

下面是过滤器,它为您提供与“hero-node *”匹配的节点的地址列表

- debug:
    msg: "{{ nodes|selectattr('Node', 'match', 'hero-node*')|map(attribute='Address')|list}}"

1
投票

我使用json_query来解析JSON响应(查询语法取决于你的JSON,语法here):

- name: set facts
    set_fact: 
      frontendip: "{{item.ip}}"
    loop: "{{facts_var | json_query(fquery)}}"
    vars:
      fquery: "Nodes[*].{ip: Address, Nodename: Node}"
    when: "'hero-node' in item.Nodename"
© www.soinside.com 2019 - 2024. All rights reserved.