简体   繁体   中英

Dynamic group assignment for ansible playbook

I'm working on an ansible playbook that will provision a redis cluster. I have 3 groups that my playbook looks in, but I can't figure out how to assign nodes to a group properly.

The problem arises because I have a dynamic number of nodes. If 2 nodes are requested I'd like to have groups that look like this:

[redis_master]
node1
[redis_slave]
node2

In the case of 3:

[redis_master]
node1
[redis_slave]
node2
[redis_sentinel]
node3

And in case of 4 etc:

[redis_master]
node1
node4
[redis_slave]
node2
[redis_sentinel]
node3

Is there a paradigm I'm missing here?

I'm not sure I understand the situation completely. Usually you pre-define all involved hosts and arrange them in groups. All hosts a playbook might process, are required to be defined in the inventory. Which hosts are processed by a playbook then is more or less fixed. What exactly do you mean by:

If X nodes are requested ...

I know you can use --limit to limit the playbook to a subset of the originally defined hosts. Also you can use a param defined in --extra-vars to pick a specific group or a set of hosts. But still they need to be pre-defined in the inventory and it seems strange (and error prone) to me to depend the groups and therefore the roles (redis master, slave etc) on the number of involved hosts.

That being said... I think inventory scripts might be what you're looking for. With those scripts you can generate the inventory dynamic. I think you can't pass params but you can export vars and read them later from the script.

Well, with Redis Sentinel, the inventory is dynamic in nature. You might define a certain host in your [redis_master] group, but the master role can be re-assigned automatically by the cluster hosts. Redis Sentinel re-writes the Sentinel config file.

So you might be surprised to login to the machine you thought was master and to find out this!!

redis-cli info replication
...
role:slave
master_host:10.1.1.20
...

Therefore, to make an idempotent role for a cluster, you will need to discover who is the master by probing hosts in the [redis_sentinel] group (assuming you run sentinel on each). And then compose the groups with something like this:

 - name: get master_host
   run_once: true
   shell: "redis-cli info replication|grep -A1 role|tail -1|cut -d: -f2"
   register: master_host

 - name: add master_host
   add_host:
     name: "{{ master_host.stdout }}"
     groups: redis_master

If you work on Centos/RHEL, consider a pull-request here please: https://github.com/dockpack/base_redis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM