Random return host in groups and balanced accross the cluster

50 views
Skip to first unread message

Nicolas G

unread,
Feb 17, 2016, 7:13:43 PM2/17/16
to Ansible Project
Hi,

I have an inventory file with the bellow servers :

# servers

[dbservers]
db01
db02
db03
db04


In my template I want to populate the config by choosing randomly one of the servers from the dbservers group .

Unfortunately the bellow will return all servers :  

{% for host in groups['dbservers'] %}
    server_address
= {{ hostvars[host]['inventory_hostname'] }}
{% endfor %}


1) I need Ansible to return only 1 server (random) .

2) I will run this on a big cluster of servers so I would like that random is actually balanced across the cluster equally or else a db servers will get more connections than the others and could hit a capacity issue.

Can someone help me ? 

Thanks in advance.
Message has been deleted
Message has been deleted

Paul Markham

unread,
Feb 17, 2016, 9:07:59 PM2/17/16
to Ansible Project
There's a random number filter; see http://docs.ansible.com/ansible/playbooks_filters.html#random-number-filter.

Try something like:


server_address = {{ groups['dbservers'] | random }}

Nicolas G

unread,
Feb 18, 2016, 2:52:26 PM2/18/16
to Ansible Project
Thank you Paul , that seems to work . However I'm not completely satisfied with how balanced the random filter has worked.

Do you know if there is a better way to have the server_address more equally balanced across a big bluster of servers ? 

Brian Coca

unread,
Feb 20, 2016, 7:15:27 PM2/20/16
to ansible...@googlegroups.com
you could probably do a mod on the length of the group and assign depending on a sequence.


​random results even out over large numbers but can be very skewed on small samples.​

----------
Brian Coca

Nicolas G

unread,
Feb 22, 2016, 7:50:57 PM2/22/16
to Ansible Project
Brian Coca can you be more specific ? I'm trying something like the bellow but I"m stuck, it's deploying all the servers in every run instead of only a random one ..

{% for host in groups['dbservers'] %}

 
{% if loop.index % (loop.length + 1) %}
server_address
= {{ host }}
   
{{ loop.index % loop.length + 1 }}
 
{% endif %}
{% endfor %}

Reply all
Reply to author
Forward
0 new messages