简体   繁体   中英

How to dynamically create an ansible list out of hostvars?

I have a few variables defined for every host. Like...

hosts:
  - hostA:
    vars:
      self_ip: "192.168.1.10"
      self_port: "8001"
  - hostB:
    vars:
      self_ip: "192.168.1.11"
      self_port: "8002"

Inside one of the roles, I want to define a variable, which is a combination of few host variables. For example...

all_endpoints: 192.168.1.10:8001,192.168.1.11:8002

How can I do this?

I tried using Jinja2 for loops like below:

rs_members:  
  "{% for host in groups['all_hosts'] %}
  - {{hostvars[host]['self_ip']}}:{{hostvars[host]['self_port']}}
  {% endfor %}"

This seems to be creating a string. Not a list. Can someone tell me what is wrong? And is there a way to use ansible filters to achieve this?

- set_fact:
    all_endpoints: "{{ hosts|json_query('[].vars.[self_ip, self_port]') }}"
- set_fact:
    touples: "{{ touples|default([]) + [ item.0 + ':' + item.1 ] }}"
  loop: "{{ all_endpoints }}"
- debug:
    var: touples

gives

"touples": [
    "192.168.1.10:8001", 
    "192.168.1.11:8002"
]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM