首页 > 解决方案 > 如何在我的剧本中使用主机来启动我的模板

问题描述

我有一本剧本来启动需要主机名的服务器的配置。我想将我在剧本中定义的主机作为组传递,以便循环我的 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

解决方案


组名没有特殊变量,但是有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 %}

推荐阅读