ansible - 如何在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模板与 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
推荐阅读
- dynamic - Power BI 是否有一个选项可以通过更新数据来更新图表
- java - mmap.setonMarkerDragListener 使我的应用程序崩溃
- reactjs - 在 React JS 渲染中放置条件 div 标签
- swift - 精灵不会移动或从墙上反弹
- html - 使用 jQuery 确定字段是否已自动填充
- r - R将行日期转换为列日
- visual-studio-code - 如何在vscode中隐藏垂直线
- javascript - 将 React 与 Bootstrap 一起使用,我想开始一行拉四个数据集,将它们放入 col 然后用下一个 4 开始一个新行
- c# - 是否 IServiceProvider.GetServices
() 总是按注册顺序返回可用的服务实现? - javascript - 了解 event.target.elements