Ansible:将configuration复制到当前和其他主机

这是一个棘手的理论问题,甚至是解释本身。

我将使用Bacula (服务器备份软件)作为示例,使其更加清晰。

Bacula有一个服务器和一个客户端组件。 添加一个新的客户端需要在服务器和客户端上的configuration文件。 所以我想要做的就是:

Bacula服务器angular色:

  1. 在一台主机上安装bacula服务器
  2. [为每个客户端]将服务器的客户端configuration文件复制到服务器
  3. [针对每个客户端]将客户端的客户端configuration文件复制到客户端

现在我host_vars的问题是host_varsgroup_vars 。 我想能够让所有我的[debian]主机(这是一个组)使用这个angular色。 所以我的剧本看起来像这样:

 - hosts: debian roles: - bacula tags: - bacula 

所以当这个angular色被触发时,它应该执行以下操作:

  1. 一个主机显然必须是服务器,所以如果在服务器主机上播放,那么这个主机就会得到完整的bacula服务器configuration。
  2. 如果将此angular色应用于所有其他客户端,则应该发生以下情况:
    1. (当前主机debian-client ):将configuration复制到debian-client
    2. (当前主机debian-client ):将configuration复制到debian-server

任何想法我怎么能做到这一点?


对我来说,这是很难解释的,所以如果上述内容不清楚,请让我知道,所以我可以说得更清楚。

更新:

感谢@Konstantin Suvorov delegate_to回答: https ://docs.ansible.com/ansible/playbooks_delegation.html#delegation

像这样的东西,例如:

库存:

 [debian] host1 host2 host3 bacula_role=server host4 host5 

玩:

 - 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 

用一些真正的模块replacedebug语句(如apt / template ),并添加一些error handling,如果没有bacula_role=server主机存在。

如果你有很多安装服务器/客户端的任务,你可以把它们拆分成bacula_server.ymlbacula_client.yml而不包括when语句,但是包含它们:

 - include: "bacula_{{ bacula_role | default('client') }}.yml"