How to update host file using ansible

Hello Team,

I am looking ansible playbook which will update host file in below scenario.

I have 2 group server both are aws instance.
[test]
servername

[test1]
servername1

I want to update host file on test group server with test1 server details like ip address and hostname.

I dont want to put ip details into inventory.

can u help me here.

I am using below playbook with set hostname on xyz server and update host file for self. I want to add abc server details into host file of xyz.

vars:

test_hostname: “xyz”

  • name: set up host name
    hostname:
    name: “{{ test_hostname }}”
    register: set_hostname
    tags:

  • set_hostname
    when: test_hostname is defined

  • name: Add host entry into host file
    lineinfile:
    dest: /etc/hosts
    regexp: ‘.*{{ ansible_nodename }}$’
    line: ‘{{ ansible_default_ipv4.address }} {{ ansible_nodename }} {{ ansible_hostname }}’
    state: present

  • name: Add other host entry
    lineinfile:
    path: /etc/hosts
    regexp: ‘.*{{ ansible_nodename }}$’
    #insertafter: ‘^{{ ansible_nodename }}’
    line: ‘{{ ansible_default_ipv4.address }} {{ ansible_nodename }}’
    when: inventory_hostname is groups[‘test1’]
    tags:

  • add_host