ansible load hosts file code example

Example 1: ansible hosts

[webserver]
192.164.0.1 ansible_password=passwd

Example 2: ansible hosts file update

---
  - name: host file update - Local DNS setup across all the servers
    hosts: multi
    gather_facts: yes
    tasks:

    - name: Update the /etc/hosts file with node name
      tags: etchostsupdate
      become: yes
      become_user: root
      lineinfile:
        path: "/etc/hosts"
        regexp: ".*\t{{ hostvars[item]['ansible_hostname']}}\t{{ hostvars[item]['ansible_hostname']}}"
        line: "{{ hostvars[item]['ansible_env'].SSH_CONNECTION.split(' ')[2] }}\t{{ hostvars[item]['ansible_hostname']}}\t{{ hostvars[item]['ansible_hostname']}}"
        state: present
        backup: yes
      register: etchostsupdate
      when: ansible_hostname != "{{ item }}" or ansible_hostname == "{{ item }}"
      with_items: "{{groups['multi']}}"