--- - name: Add IP address of all hosts to all hosts become: yes lineinfile: dest: /etc/hosts regexp: '.*{{ item }}$' line: "{{ hostvars[item].ansible_host }} {{item}}{% if gen_tls_tld is defined %} {{ item }}.{{ gen_tls_tld }}{% endif %}" state: present when: hostvars[item].ansible_host is defined loop: "{{ groups.all }}"