Ansible Pilot

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.

November 24, 2021
Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons

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

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 ansible.builtin.copy module or for empty file Ansible ansible.builtin.file module. For Windows, use the ansible.windows.win_template module instead.

Parameters

Let me highlight the most useful parameters for the template module. The only required parameters are “src” and “dest”. The “src” parameter specifies the template file name. Templates usually are stored under “templates” directories with “.j2” file extension. The “dest” parameter specifies the path where to render the template to on the remote machine. The “validate” parameters allow you to specify the validation command to run before copying it into place. It’s very useful with configuration files for services. Please note that the special escape sequence “%s” is going to be expanded by Ansible with the destination path. If the “backup” parameter is enabled Ansible creates a backup file including the timestamp information before copying it to the destination. Let me also highlight that we could also specify the permissions and SELinux properties.

The Best Resources For Ansible

Certifications

Video Course

Printed Book

eBooks

demo

Loop in file template with Ansible Playbook. You could find more information about Magic Variables: https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html

code

---
- name: template module demo
  hosts: all
  become: true
  tasks:
    - name: generate /etc/myhosts file
      ansible.builtin.template:
        src: templates/hosts.j2
        dest: /etc/myhosts
        owner: root
        group: root
        mode: '0644'
# {{ ansible_managed }}
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
{% for host in group['all'] %}
{{ hostvars[host]['ansible_host'] }} {{ hostvars[host]['inventory_hostname'] }} {{ hostvars[host]['inventory_hostname_short'] }}
{% endfor %}

execution

$ ansible-playbook -i apply\ template/inventory apply\ template/generate_myhosts.yml

PLAY [template module demo] ***********************************************************************

TASK [Gathering Facts] ****************************************************************************
ok: [demo.example.com]

TASK [generate /etc/myhosts file] *****************************************************************
changed: [demo.example.com]

PLAY RECAP ****************************************************************************************
demo.example.com           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

before execution

$ ssh [email protected]
Last login: Tue Nov 23 17:10:30 2021 from 192.168.0.101
[devops@demo ~]$ sudo su
[root@demo devops]# ls -al /etc/myhosts
ls: cannot access '/etc/myhosts': No such file or directory
[root@demo devops]# 

after execution

$ ssh [email protected]
Last login: Tue Nov 23 17:32:39 2021 from 192.168.0.101
[devops@demo ~]$ sudo su
[root@demo devops]# ls -al /etc/myhosts 
-rw-r--r--. 1 root root 214 Nov 23 17:32 /etc/myhosts
[root@demo devops]# cat /etc/myhosts 
# Ansible managed
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.190  demo.example.com demo
[devops@demo ~]$ exit
logout
Connection to demo.example.com closed.
ansible-pilot $ cat apply\ template/inventory 
demo.example.com ansible_host=192.168.0.190

[all:vars]
ansible_connection=ssh
ansible_user=devops

code with ❤️ in GitHub

Recap

Now you know how to use a for loop in a Jinja2 template file with Magic Variables with Ansible. Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Want to keep this project going? Please donate

Access the Complete Video Course and Learn Quick Ansible by 200+ Practical Lessons
Follow me

Subscribe not to miss any new releases