如何在ansible中枚举主机?

How to enumerate hosts in 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 |

有办法实现吗?

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

要获取清单组中当前主机的索引,您可以在组列表中使用index方法。

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

例子

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


原回答
如果将 jinja2 templates with ansible you can access the index in a for loop{{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 template 模块。

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

你可以 运行 朝着 localhost 的方向发展,当涉及到 lineinfile 任务时,你应该将 delegate_to 选项添加到 运行每个主机的任务。

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

- 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

希望对您有所帮助