“Jinja2模板“hosts.j2”用于在每个节点上创建主机文件不起作用。”

huangapple go评论79阅读模式
英文:

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 %}

huangapple
  • 本文由 发表于 2023年7月12日 20:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定