首页 > 解决方案 > 如何在ansible中枚举主机?

问题描述

我是使用 Ansible 并使用它来自动配置主从节点集群的新手。

我有一个主机文件分为两组:

[master]
masternode

[slaves]
slavenode0
slavenode1

我想要的是遍历从属组,以便使用从属组中的位置索引更新远程机器上文件中的一行。

当我尝试使用“with_items”或“with_indexed_items”执行此操作时,问题是该文件在从属组中的每台机器上得到更新,对应于从属组中从属节点的数量。这意味着每个从节点上的每个文件最终都插入了完全相同的行,只是该文件被更新了 x 次。

所以我想要:

| slave node | filename | line in file     |
| slave0     |  test    | slave index is 0 |
| slave1     |  test    | slave index is 1 |

我得到的是:

| slave node | filename | line in file     |
| slave0     |  test    | slave index is 1 |
| slave1     |  test    | slave index is 1 |

有没有办法做到这一点?

标签: ansibleansible-2.x

解决方案


编辑
重新阅读您的问题后,我想我误解了它。

要获取库存组中当前主机的索引,可以使用index组列表中的方法。

{{groups['slaves'].index(inventory_hostname)}}

例子

- lineinfile:
    path: ~/test
    line: "slave index is {{groups['slaves'].index(inventory_hostname)}}"


原始答案
如果您将jinja2模板与 ansible 一起使用,您可以在for 循环中使用{{loop.index}}.

从属配置的示例模板可能如下所示

| slave node | filename | line in file |
{% for slave in groups['slaves'] %}
| {{slave}} | test | slave index is {{loop.index}} |
{% endfor %}

这应该有所需的输出

| slave node | filename | line in file |
| slavenode0 | test | slave index is 1 |
| slavenode1 | test | slave index is 2 |

要在你的剧本中使用它,你可以使用 ansible模板模块。

tasks:
  - name: master slave configuration
    template: src=slave.conf.j2 dest=/etx/slave.conf

推荐阅读