问题原文
原帖链接 · cytopia · CC BY-SA 3.0
this is a tricky theoretical question, even the explanation itself.
I will use Bacula (server backup software) as an example here to make it more clear.
Bacula has a server and a client component. Adding a new client requires a config file on the server and on the client. So what I want to do in my role is:
Bacula server role:
- Setup the bacula server on one host
- [for every client] Copy client config file for the server to the server
- [for every client] Copy client config file for the client to the client
Now the problem I have is with host_vars and group_vars. I want to be able to have this role used by all my [debian] hosts (this is a group).
So my playbook looks like this:
- hosts: debian
roles:
- bacula
tags:
- bacula
So when this role is triggered it should do the following:
- One host must obviously the server, so this one will get a complete bacula server provision if it is played out on the server host.
- If this role is applied to all other clients the following should happen:
- (current host
debian-client): copy config todebian-client - (current host
debian-client): copy config todebian-server
- (current host
Any idea how I could do that?
For me it is really hard to explain, so if anything about the above is unclear, please let me know so i can make it clearer.
Update:
Thanks to @Konstantin Suvorov delegate_to answered it: https://docs.ansible.com/ansible/playbooks_delegation.html#delegation
已采纳解答
原帖链接 · Konstantin Suvorov · CC BY-SA 3.0
Something like this, for example:
inventory:
[debian]
host1
host2
host3 bacula_role=server
host4
host5
play:
- hosts: debian
vars:
bacula_server: "{{ (ansible_play_hosts | map('extract',hostvars) | selectattr('bacula_role','defined') | selectattr('bacula_role','equalto','server') | first).inventory_hostname }}"
tasks:
- debug: msg="Install server"
when: inventory_hostname == bacula_server
# client block
- block:
- debug: msg="Template server-side client config"
delegate_to: bacula_server
- debug: msg="Template client config"
when: inventory_hostname != bacula_server
# end of block
Replace debug statements with some real module (e.g. apt/template) and add some error handling if not hosts with bacula_role=server exist.
If you have many tasks to install server/client, you may split them into bacula_server.yml and bacula_client.yml without when statements but include them with:
- include: "bacula_{{ bacula_role | default('client') }}.yml"
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
