0

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.

DDStackoverflow
  • 505
  • 1
  • 11
  • 26
  • you should try to use a `debug` task to inspect how the `nodes` var looks like. maybe you need to use the `nodes.results` to loop through. or please update the question by posting how the `nodes` variable looks like to assist you – ilias-sp Mar 11 '19 at 23:27
  • sorry for not clear, updated the questions, `json` response data = `nodes`. hope it's clear now. – DDStackoverflow Mar 12 '19 at 03:28

2 Answers2

1

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}}"
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
1

i use json_query to parse through JSON responses (query syntax depends on your JSON, syntax 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"
jo_
  • 33
  • 6