Random return host in groups and balanced accross the cluster

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.

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 }}

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 ?

you could probably do a mod on the length of the group and assign depending on a sequence.

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 %}

`