Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanity check before running ansible playbook -> count hosts

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:

  • Is there exactly one proxy? (1 host in group A)
  • Is there at least one redis node (>=1 host in group B)

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?

like image 393
udondan Avatar asked Jul 07 '14 08:07

udondan


2 Answers

(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
like image 118
wazy Avatar answered Oct 10 '22 22:10

wazy


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'])
like image 21
Woodham Avatar answered Oct 11 '22 00:10

Woodham