如何在ansible中枚举主机?

如何在ansible中枚举主机?,ansible,ansible-2.x,Ansible,Ansible 2.x,我不熟悉使用Ansible并使用它自动配置主从节点集群 我将主机文件分为两组: [master] masternode [slaves] slavenode0 slavenode1 我想要的是遍历slaves组,这样远程机器上的文件中的一行就会用slaves组中的位置索引更新 当我尝试使用“with_items”或“with_indexed_items”执行此操作时,问题是文件在从属组中的每台计算机上都会更新,与从属组中的从属节点数量相对应。这意味着每个slavenode上的每个文件都插入了

我不熟悉使用Ansible并使用它自动配置主从节点集群

我将主机文件分为两组:

[master]
masternode

[slaves]
slavenode0
slavenode1
我想要的是遍历slaves组,这样远程机器上的文件中的一行就会用slaves组中的位置索引更新

当我尝试使用“with_items”或“with_indexed_items”执行此操作时,问题是文件在从属组中的每台计算机上都会更新,与从属组中的从属节点数量相对应。这意味着每个slavenode上的每个文件都插入了完全相同的行,只是文件更新了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 |
有没有办法做到这一点?

编辑
重读你的问题后,我想我误解了

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

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

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

原始答案
如果将模板与ansible一起使用,则可以通过
{{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模块


您可以向
localhost
运行该播放,当涉及到
lineinfle
任务时,您应该添加
delegate\u to
选项,以向每个主机运行该任务

您没有包含
lineinfle
代码,因此我无法为您调整它,但您可以看到下面的示例,该示例演示了每个主机的索引增量:

- name: Print index of each host
  shell: "wall 'this is iteration: #{{ index_no}}'"
  delegate_to: "{{ item }}"
  loop: "{{ groups['is_hosts'] }}"
  loop_control:
    index_var: index_no

希望能帮上忙

很高兴能帮上忙!为了提高可搜索性,编辑问题的标题可能会很好,但如果没有您的反馈,我不想这样做……当然,请放心,我发现很难描述问题,所以如果您有更好的问题,请尝试!
- name: Print index of each host
  shell: "wall 'this is iteration: #{{ index_no}}'"
  delegate_to: "{{ item }}"
  loop: "{{ groups['is_hosts'] }}"
  loop_control:
    index_var: index_no