0

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 Answers1

0

I also tried blockinfile ...

A minimal example playbook

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

U880D
  • 8,601
  • 6
  • 24
  • 40