ansible - 如何在我的剧本中使用主机来启动我的模板
问题描述
我有一本剧本来启动需要主机名的服务器的配置。我想将我在剧本中定义的主机作为组传递,以便循环我的 jinja2 模板中的变量。而且我不想在vars中设置主机(因为已经在剧本中定义了,我不知道重新定义的原因)
例如:主机文件:
[test_servers]
t1
t2
t3
[test2_servers]
t2
t4
剧本:
- hosts: test_servers
tasks:
- name: generate my conf
template:
src: templates/temp.conf.j2
dest: "test.conf"
force: True
vars:
hosts: test_servers # So far I need to declare the var here duplicately, I've group my server in host file and I just want to use the current group.
临时配置文件
....
{% for host in groups[hosts] %}
Entry.{{ loop.index }} = {{ host }}
{% endfor %}
....
我想知道是否有更好的方法将 playbook 中设置的主机传递给我的 jinja2 模板,以便我可以将 playbook 重新用于不同的主机。例如,我只需要将 playbook hosts 重置为 test2,无需重写 vars。
解决方案
组名没有特殊变量,但是有ansible_play_hosts_all
该剧针对的所有主机列表
移除vars并在模板中使用ansible_play_hosts_all
- hosts: test_servers
tasks:
- name: generate my conf
template:
src: templates/temp.conf.j2
dest: "test.conf"
force: True
{% for host in ansible_play_hosts_all %}
Entry.{{ loop.index }} = {{ host }}
{% endfor %}
推荐阅读
- go - dog 没有实现宠物(speak 方法的类型错误)
- performance - 一个计算如何从经过的时间计算 FLOPS?
- reactjs - 如何在 ReactJS 中路由到新页面
- r - ggplot的中位数统计差异
- javascript - 如何在页面加载时请求,反应钩子
- javascript - 如何将变量添加到 xhr.open outta Chrome 扩展?
- powerquery - 在 PowerQuery 中将列强制转换为其他类型
- python - 如何在一个目录中为一个项目创建多个 docker 镜像?
- node.js - 无法从端点下载 GraphQL 架构
- javascript - 那么 Javascript 库已经带有 GUI 了吗?