英文:
Ansible Playbook - Adding entries into /etc/hosts file
问题
我正在尝试从清单文件中读取主机:
# PostgreSQL 节点
[all]
192.168.63.31 hostname=pgnode1
192.168.63.32 hostname=pgnode2
192.168.63.33 hostname=pgnode3
并将它们添加到所有这些节点的 /etc/hosts 文件中,格式如下:
192.168.63.31 pgnode1
192.168.63.32 pgnode2
192.168.63.33 pgnode3
我尝试过:
- name: 更新主机文件
lineinfile:
state: present
dest: /etc/hosts
line: "{% for host in groups.all %} {{ host }} {{ hostvars[host]['hostname'] }} {% endfor %}"
我还尝试过 `blockinfile`,但它添加在以下格式而不是分开的行:
192.168.63.32 pgnode2 192.168.63.33 pgnode3 192.168.63.31 pgnode1
我尝试了我能找到的一切,但没有成功。请帮忙解决这个问题。提前感谢。
英文:
I am trying to read hosts from inventory file:
# PostgreSQL nodes
[all]
192.168.63.31 hostname=pgnode1
192.168.63.32 hostname=pgnode2
192.168.63.33 hostname=pgnode3
And add them to /etc/hosts file of all these nodes in the format below:
192.168.63.31 pgnode1
192.168.63.32 pgnode2
192.168.63.33 pgnode3
I have tried:
- name: update host file
lineinfile:
state: present
dest: /etc/hosts
line: "{% for host in groups.all %} {{ host }} {{ hostvars\[host\]\['hostname'\] }} {% endfor %}"
I also tried blockinfile
but it adds in this format not in separate lines:
192.168.63.32 pgnode2 192.168.63.33 pgnode3 192.168.63.31 pgnode1
I have tried whatever I could find but no luck. Please help with this. Thanks in advance.
答案1
得分: 0
---
- 主机: 本地主机
成为: false
收集事实: false
任务:
- blockinfile:
状态: 存在
目的地: etc_hosts
内容: |
{% for host in groups.all %}
{{ host }}
{% endfor %}
- lineinfile:
状态: 存在
目的地: etc_hosts
行: |
{% for host in groups.all %}
{{ host }}
{% endfor %}
这是由于line:
的格式所致。也可以使用以下格式:
- lineinfile:
状态: 存在
目的地: etc_hosts
行: |
{% for host in groups.all %}
{{ host }}
{% endfor %}
然而,该任务不是幂等的,并会多次添加行。
类似的问答
<details>
<summary>英文:</summary>
> _I also tried `blockinfile` ..._
A minimal example playbook
```lang-yaml
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- blockinfile:
state: present
dest: etc_hosts
content: |
{% for host in groups.all %}
{{ host }}
{% endfor %}
will result into requested output.
> ... but it adds in this format not in separate lines
This is because of the format of line:
. It will also work with a format like
- lineinfile:
state: present
dest: etc_hosts
line: |
{% for host in groups.all %}
{{ host }}
{% endfor %}
However, the task will not be idempotent and add the lines several times.
Similar Q&A
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论