Loop in file template — Ansible module template — Generate hosts file

How to use for loop in Ansible module template to generate/etc/myhosts file with IP address, hostname, and short name from Ansible inventory. Ansible Playbook, Jinja2 template, and with Magic Variables included.

Ansible Pilot
5 min readNov 24, 2021


How to use a loop in a file template to the target host with Ansible?

This is extremely useful for service configuration files, placeholder web pages, reports, and so much more use cases.

I’m going to show you a live demo with some simple Ansible code.

I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

Ansible loop in file template

  • ansible.builtin.template
  • Template a file out to a target host
  • ansible_managed, template_host, template_uid, template_path, template_fullpath, template_destpath, and template_run_date

Today we’re talking about the Ansible module template.

The full name is ansible.builtin.template, it’s part of `ansible-core` and is included in all Ansible installations.

It templates a file out to a target host. Templates are processed by the Jinja2 templating language.

Also you could use also some special variables in your templates: `ansible_managed`, `template_host`, `template_uid`, `template_path`, `template_fullpath`, `template_destpath`, and `template_run_date`.

It supports a large variety of Operating Systems.

For basic text formatting, use the `ansible.builtin.copy` module or for empty file `ansible.builtin.file` module.

For Windows, use the `ansible.windows.win_template` module instead.


  • src path — template (“templates/” dir)
  • dest path — target location
  • validate string — validation command before (“%s”)



Ansible Pilot

I help creative Automation DevOps, Cloud Engineer, System Administrator, and IT Professional to succeed with Ansible Technology to automate more things everyday