英文:
Jinja2 Template "hosts.j2" Used to Create Hosts File on Each Node is Not Working
问题
我想使用Jinja2模板在由Ansible控制的每个节点上创建主机文件。
模板命名为hosts.j2,其中包含以下代码:
{# 这是/etc/hosts文件的模板 #}
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ inventory_hostname }}
{% endfor %}
Ansible playbook如下:
---
- name: 使用Jinja 2模板部署主机文件
hosts: all
become: true
tasks:
- name: 创建主机文件
template:
src: hosts.j2
dest: /etc/hosts
owner: root
group: root
mode: "0644"
Playbook执行后,主机文件将在每个节点上创建,但对于每个唯一的IP地址,主机名只是重复的,如下所示:
192.xxx.xxx.xxx zoo1
192.xxx.xxx.xxy zoo1
...
在host2上:
192.xxx.xxx.xxx zoo2
192.xxx.xxx.xxy zoo2
有人可以提供如何获取每个节点主机文件中每个唯一IP地址的适当主机名的指导吗?
英文:
I want to use a Jinja2 template to create hosts files on each of the nodes controlled by Ansible.
The template is named hosts.j2 and it consists of the following code:
{# This is the template for the /etc/hosts file #}
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ inventory_hostname }}
{% endfor %}
The ansible playbook is:
---
- name: Deploy hosts files using a Jinja 2 template
hosts: all
become: true
tasks:
- name: Create hosts files
template:
src: hosts.j2
dest: /etc/hosts
owner: root
group: root
mode: "0644"
The playbook executes and the hosts files are created on each node, but for each unique IP address, the hostname is simply repeated for each unique IP address ie..,
192.xxx.xxx.xxx zoo1
192.xxx.xxx.xxy zoo1
...
On host2:
192.xxx.xxx.xxx zoo2
192.xxx.xxx.xxy zoo2
Can someone provide guidance on how to obtain the appropriate hostname for each unique IP address in each node's hostfiles?
答案1
得分: 1
这就是你需要的翻译:
{%for host in groups['all']%}
{{hostvars[host]['ansible_facts']['default_ipv4']['address']}}
{{hostvars[host]['ansible_facts']['fqdn']}} {{hostvars[host]['ansible_facts']['hostname']}}
{% endfor %}
英文:
There you go.
{%for host in groups['all']%}
{{hostvars[host]['ansible_facts']['default_ipv4']['address']}}
{{hostvars[host]['ansible_facts']['fqdn']}} {{hostvars[host]['ansible_facts']['hostname']}}
{% endfor %}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论