List of all ansible_ssh_host in group

673 views
Skip to first unread message

Andrew Teil

unread,
Sep 14, 2015, 10:56:21 AM9/14/15
to Ansible Project
Hi. I have the following inventory structure

master1 ansible_ssh_host=10.0.45.11
master2 ansible_ssh_host=10.0.45.12
master3 ansible_ssh_host=10.0.45.13
slave1 ansible_ssh_host=10.0.45.51
slave2 ansible_ssh_host=10.0.45.52
slave3 ansible_ssh_host=10.0.45.53

[master_servers]
master1
master2
master3

...

Now I need a URL that looks something like this zk://10.0.45.11:2181,10.0.45.12:2181,10.0.45.13:2181/mesos
For that reason I need a list of ansible_ssh_host variables for all servers in the group master_servers.

I ended up with this
[hostvars[groups['master_servers'][0]].ansible_ssh_host, hostvars[groups['master_servers'][1]].ansible_ssh_host, hostvars[groups['master_servers'][2]].ansible_ssh_host]

but this solution takes only three servers not all in the group

Matt Martz

unread,
Sep 14, 2015, 11:02:58 AM9/14/15
to ansible...@googlegroups.com
We do something like this for our mongodb connection string:

'mongodb://{% for h in groups.database %}{{ h }}{% if not loop.last %},{% endif %}{% endfor %}/{{ mongo_database }}?replicaSet={{ mongo_replicaset }}'


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/b3c8e2fe-ec8c-4655-88eb-cc5813c08673%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Matt Martz
@sivel
sivel.net

Takeshi Yaegashi

unread,
Sep 14, 2015, 10:11:00 PM9/14/15
to Ansible Project
Hello,

You can achieve it by using the following jinja2 template:

---
- hosts: localhost
  gather_facts: no
  vars:
    zkurl: |
      {%- set o = [] %}
      {%- for i in groups.master_servers %}
      {%-   if o.append(hostvars[i].ansible_ssh_host+':2181') %}
      {%-   endif %}
      {%- endfor %}
      zk://{{ ','.join(o) }}/mesos
  tasks:
    - debug:
        var: zkurl

Sample session:

$ ansible-playbook -i hosts zk.yml

PLAY [localhost] ************************************************************** 

TASK: [debug ] **************************************************************** 
ok: [localhost] => {
    "var": {
    }
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=1    changed=0    unreachable=0    failed=0   
Regards,
-- 
YAEGASHI Takeshi <yaeg...@debian.org
Reply all
Reply to author
Forward
0 new messages