Search code examples
ansibleansible-2.xconsul

Ansible playbook for getting an attribute from returned json data


I am new to Ansible and this my first attempt to it. I have a task to retrieve an attribute Address from a consul nodes end point. My play looks like below

- 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 }}"

here I'm trying to get all the nodes from consul then filter out the Addresses of node containing hero_node in name of the node but I'm getting an exception as

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

the nodes json return from the end point looks like this:

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

Any help would be really appreciated.


Solution

  • Below is the filter that gives you the list of addresses of nodes that match "hero-node*"

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