Is it possible build a file in local by using template module?

Now,the template module woule build the template file and send to the remote host.
Is it possible for not send to the remote host?

I just want to see the file in local machine.

Yep. The basics are that you could do:

  • local_action: template src=src.j2 dest=/path/to/local/system

However, this is a bit of a trap, if you are iterating over 500 hosts in a group, this will run 500 times, and clobber the file 500 times, possibly from multiple processes at once.

So this is better:

  • hosts: webservers
    tasks:

  • blah

  • blah

  • hosts: localhost
    tasks:

  • template:

  • hosts: webservers
    tasks:

  • more

  • more

Etc.

- local_action: template src=src.j2
dest=/path/to/local/system/{{inventory_hostname}}_templateresult

Absolutely. I use this technique to help combat the deprecation of include + with_items. Something like:

- name: normalize apache_sites_list into variable file
local_action: template dest={{ apache_sites_var_file }} src="apache_sites_normalized.j2"

- name: load normalized `apache_sites_normalized` from variable file
include_vars: "{{ apache_sites_var_file }}"

- name: remove variable file
local_action: file path={{ apache_sites_var_file }} state=absent

where apache_sites_var_file is defined as:

apache_sites_var_file: /tmp/ansible.apache_sites.{{ inventory_hostname }}.yml

NOTE that it uses {{ inventory_hostname }} to help prevent issues with parallel execution.

May be an “anti pattern” in this establishment; but helped me write cleaner playbooks.

I’m not even sure I’d call it a pattern :slight_smile:

Writing variables to a template should be totally unneccessary if you’re just going to load it in that way, because of the way lazy-loading in Ansible already works.

If you want dog to contain the value of cat, you can just predeclare dog:

dog: “{{ cat }}”

You don’t have to write a variable file to load it.