I am trying to dynamically build the inventory of an "elasticsearch" cluster using the add_hosts module.
I have these tasks:
In the first task (Identify ES nodes in cluster), I query the elasticsearch API to get the names of the nodes and save it in the "es_nodes" array
- name: Identify ES nodes in cluster
uri:
url: http://localhost:9200/_nodes/_all/ip
method: GET
return_content: yes
body_format: json
failed_when: false
register: es_nodes
In the second (Extract Node Names), I extract the names of the nodes and save them in a "nodo" array
- name: Extract Node Names
set_fact:
nodo: "{{ es_nodes.json.nodes | map('regex_search', '([^\\s]+)') | select('string') | list }}"
And in the third (Create new var for IP Node), (I try, but I can't) get the IP using a loop with the names of the nodes. I manage to print the name of the variable "es_nodes.json.nodes. < nodo > .ip" but I cannot print the content, that is, the IP!
- name: Create new var for Node IP
set_fact:
nodo_ip: es_nodes.json.nodes.{{ item }}.ip
with_items: "{{ nodo }}"
In the verbose output show:
ok: [<ansible_ip>] => (item=GxcbPcQ0Qe6vSFOde0zFwg) => {"ansible_facts": {"nodo_ip": "es_nodes.json.nodes.GxcbPcQ0Qe6vSFOde0zFwg.ip"}, "changed": false, "item": "GxcbPcQ0Qe6vSFOde0zFwg"}
ok: [<ansible_ip>] => (item=V2bdDTnwTCexY67U36YE8g) => {"ansible_facts": {"nodo_ip": "es_nodes.json.nodes.V2bdDTnwTCexY67U36YE8g.ip"}, "changed": false, "item": "V2bdDTnwTCexY67U36YE8g"}
My final intention is to obtain an array with the IPs of the elasticsearch cluster "node_ip" to dynamically add them to the inventory with "add_hosts" and be able to work on the host group: "elasticsearch-security"
I imagine it would be something like this:
- name: Add host to group elasticsearch-security
add_host:
name: "{{ item }}"
groups: elasticsearch-security
with_items: "{{ nodo_ip }}"
I would appreciate your ideas to know the correct syntax to print the IP and not the name of the node in the third task or a "different" way of doing the same to create the inventory dynamically.
If I'll well understood, you need to build a variable from the content of another var (got from with_items) and then retrieve the contents of the variable.
One possibility is to create a separate playbook which will be included from the main script and use with_items on the include tasks. Here is a simple example that you can adapt to your case:
Main playbook:
- hosts: localhost
vars:
es_nodes_x: "val x"
es_nodes_y: "val y"
tasks:
# Create new var for Node IP
- include: sub.yml param={{item}}
with_items:
- "x"
- "y"
Included playbook (sub.yml):
- set_fact:
v: "{{param}}"
- debug:
msg: "{{ vars['es_nodes_' + v] }}"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.