I have a playbook that will setup a redis cluster and nutcracker as a proxy. Which hosts play which roles is defined per groups. I'd like to add a sanity check in front of running the tasks, that is:
I already have a solution, though I think it's pretty ugly and thought there has to be something better, but I just can't find it. I currently run a local task calling the playbook again with the --list-hosts parameter and check the output.
- name: Make sure there is only one proxy defined
shell: ansible-playbook -i {{ inventory_file }} redis-cluster.yml --tags "redis-proxy" --list-hosts
register: test
failed_when: test.stdout.find("host count=1\n") == -1
changed_when: 1 == 2
That works but isn't there a simply way to check the number of hosts in a group without this extra call?
(Disclaimer: I felt that I after having a similar problem and figuring it out that I should correct the other answer given here.)
What Woodham mentioned about using Jinja2 filters is correct but was used incorrectly. They can be used in playbooks but you should use them in this fashion:
vars:
num_hosts: "{{ groups['redis-proxy'] | length }}"
As you can see we can chain filters this way easily and later on we can have a check on this variable:
- name: Validate Number of Nodes
fail: msg="The number of nodes must be exactly 1!"
when: num_hosts | int != 1
You should be able to do this using magic variables. (See Ansible documentation here: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts)
To get the number of hosts in a group, you can get the group using groups['group_name']
. Then you can use the Jinja2 fileter length
(http://jinja.pocoo.org/docs/templates/#length) to get the length of that group.
E.g. (in a playbook)
vars:
num_redis_proxy_hosts: length(groups['redis-proxy'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With