+-
ANSIBLE: 如何从清单组附加变量

我有一个ansible清单,组别如下。

  +hosts/
  +all/
  +group_vars/
    - linux.yml
    - webserver.yml
    - dbserver.yml
...

我有一个游戏本,用来设置对主机的监控,而监控的种类是由插件完成的。所以在每个组y中设置一个列表 monitoring_plugins 的插件,以便能够监控每个服务。 在每一个组的yml中,我尝试着将其 "追加 "到列表中。

monitoring_plugins: {{ monitoring_plugins|default([]) + [ 'whatever_plugin_correspond_to_group' ] }}

但这并没有达到预期的效果 如果一个主机属于多个组,它应该有对应于这些组的插件。

有什么方法可以实现这一点吗?

先谢谢你。

2
投票

你所描述的应该可以正常工作。在任务中但你不可能在一个可执行的代码里有一个 varsgroup_vars yaml或json文件--这些都是静态的。

所以你需要在低层设置一个独特的名称,然后在顶层将它们滚动起来。

group_vars/
  dbserver.yml  # sets monitoring_plugins_dbserver: ["a", "b"]
  linux.yml     # sets monitoring_plugins_linux: ["c", "d"]

然后在你的任务中,像这样(但要提醒你,我还没有测试过。此例):

- set_fact:
    monitoring_plugins: >-
      {% set results = [] %}
      {% for g in groups.keys() %}
      {% set _ = results.extend(vars['monitoring_plugins_'+g]|d([])) %}
      {% endif %}
      {{ results }}