nerdexam
Red_Hat

EX294 · Question #10

10. Generating Host File After running this playbook, the file /etc/myhosts on hosts in the dev host group should contain one line for each managed host, as follows: 127.0.0.1 localhost…

This playbook generates a custom /etc/myhosts file on hosts within the dev group, containing static localhost entries and dynamic host-specific entries derived from inventory facts.

Submitted by tarun92· Apr 18, 2026Manage Variables, Facts, and Content

Question

  1. Generating Host File After running this playbook, the file /etc/myhosts on hosts in the dev host group should contain one line for each managed host, as follows: 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 172.25.250.9 node1.lab.example.com node1 172.25.250.10 node2.lab.example.com node2 172.25.250.11 node3.lab.example.com node3 172.25.250.12 node4.lab.example.com node4 172.25.250.13 node5.lab.example.com node5 Note: The order of display of inventory host names is not important. Correct Answer: See the below explanation Explanation Explanation/Reference: Solution: [greg@control ansible]$ ansible dev -m debug -a 'var=groups' [greg@control ansible]$ ansible dev -m debug -a "var=groups['all']" [greg@control ansible]$ vim hosts.j2 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 {% for i in groups['all'] %} {% endfor %} [greg@control ansible]$ vim hosts.yml --- - name: gen host file hosts: all tasks: - name: Template a file to /etc/myhosts template: src: /home/greg/ansible/hosts.j2 dest: /etc/myhosts when: inventory_hostname in groups.dev [greg@control ansible]$ ansible-navigator run hosts.yml -m stdout # Verification (mandatory operation) [greg@control ansible]$ ansible dev -m shell -a 'cat /etc/myhosts'

Explanation

This playbook generates a custom /etc/myhosts file on hosts within the dev group, containing static localhost entries and dynamic host-specific entries derived from inventory facts.

Concept tested. Ansible templating with inventory facts

Reference. https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html

Topics

#Jinja2 Templating#Ansible Variables#Template Module#Conditional Logic

Community Discussion

No community discussion yet for this question.

Full EX294 Practice