Reputation: 1772
I use Ansible to create a multi-server environment, within which are two sets of database servers in a master-slave configuration, so four hosts in all.
My inventory file is currently set-up as follows:
[dbmaster]
set1-db-master
set2-db-master
[dbslave]
set1-db-slave
set2-db-slave
In the playbooks I generally make use of when
clauses to distinguish between masters and slaves as a part of the overall installation. For example:
- name: Stop the Slave Database.
command: systemctl stop mysql
when: inventory_hostname in groups['dbslave']
Which works fine for most tasks. However I now have one particular problem and I can't think of a neat way of solving it. When setting up the master/slave configurations I have to be able to tie the relevant master and slaves together, but there are more than one of each!
That is set1-db-slave
has to know which master it needs to point to:
set1-db-master
, or set2-db-master
.
I'm guessing that the process would be to:
groups['dbslave']
array, and groups.dbslave[i]
But is this a safe assumption to make about the array positions? And even then I'm not sure of the syntax for achieving this.
Upvotes: 1
Views: 244
Reputation: 68294
Q: "How to identify related hosts?"
A: It's possible to create a dictionary and use it later. For example
- hosts: all
tasks:
- set_fact:
dbsrv: "{{ dict(groups.dbmaster|sort|zip(groups.dbslave|sort)) }}"
run_once: true
- debug:
var: dbsrv
run_once: true
- hosts: dbmaster
tasks:
- debug:
msg: "Related slave: {{ dbsrv[inventory_hostname] }}"
gives
ok: [set1-db-master] => {
"dbsrv": {
"set1-db-master": "set1-db-slave",
"set2-db-master": "set2-db-slave"
}
}
ok: [set1-db-master] => {
"msg": "Related slave: set1-db-slave"
}
ok: [set2-db-master] => {
"msg": "Related slave: set2-db-slave"
}
Q: "But is this a safe assumption to make about the array positions?"
A: It's possible to create alphabetical relations (e.g. set1-db-master: set1-db-slave) and use the sort
filter
dbsrv: "{{ dict(groups.dbmaster|sort|zip(groups.dbslave|sort)) }}"
Upvotes: 1