Sanity check before running ansible playbook -> count hosts

ansibleansible-playbook

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?

Best Answer

(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
Related Topic