在Ansible中,可以使用模板来生成动态的主机列表。以下是一个示例代码,演示如何使用Ansible模板来生成一个排除当前主机的主机列表:
首先,在Ansible的inventory文件中定义一个群组,用于包含所有的主机:
[all_hosts]
host1
host2
host3
在Ansible Playbook中,使用set_fact
模块来获取当前主机的主机名:
- name: Get current hostname
set_fact:
current_host: "{{ inventory_hostname }}"
创建一个模板文件,用于生成排除当前主机的主机列表。模板文件的内容如下:
{% for host in groups['all_hosts'] %}
{% if host != current_host %}
{{ host }}
{% endif %}
{% endfor %}
使用template
模块来渲染模板文件,并将结果保存到一个变量中:
- name: Render host list template
template:
src: host_list_template.j2
dest: /tmp/host_list.txt
register: rendered_template
最后,可以在Ansible Playbook中使用生成的主机列表:
- name: Print host list
debug:
var: rendered_template.stdout_lines
以上代码将生成一个主机列表文件/tmp/host_list.txt
,其中排除了当前主机。同时,在后续的任务中,可以使用rendered_template.stdout_lines
变量来引用生成的主机列表。
希望以上解决方案能对你有所帮助!
上一篇:Ansible模板追加到文件