Health check before launching the available playbook & # 8594; number of hosts

I have a playbook that will configure a redis cluster and nutcracker as a proxy. What hosts play, what roles are defined for each group. I would like to add a health check before completing tasks, namely:

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

I already have a solution, although I find it pretty ugly and thought there should be something better, but I just can't find it. I am currently running a local task that calls the playbook again with the -list-hosts option 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 

This works, but is there no easy way to check the number of hosts in a group without this extra call?

+7
ansible ansible-playbook
source share
2 answers

(Disclaimer: I felt like I was having a similar problem and found out that I have to fix another answer given here.)

What Woodham mentioned about using Jinja2 filters is true, but was misused. They can be used in books, but you should use them this way:

 vars: num_hosts: "{{ groups['redis-proxy'] | length }}" 

As you can see, we can easily filter the filters this way, and later we can check this variable:

 - name: Validate Number of Nodes fail: msg="The number of nodes must be exactly 1!" when: num_hosts | int != 1 
+21
source share

You must do this using magic variables. (See Ansible's 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 length file file ( http://jinja.pocoo.org/docs/templates/#length ) to get the length of this group.

eg. (in the textbook)

 vars: num_redis_proxy_hosts: length(groups['redis-proxy']) 
+1
source share

All Articles