Ansible remote templates

You’ve got two options here if your template is going to be on the remote host.

Firstly, you can use the fetch module which works as pretty much the opposite to the copy module to bring the template back after cloning the repo on the remote host.

A playbook for this might look something like:

- name : clone repo on remote hosts
  git  :
    repo : {{ git_repo_src }}
    dest : {{ git_repo_dest }}

- name     : fetch template from single remote host
  run_once : true
  fetch    :
    src             : {{ template_path }}/{{ template_file }}
    dest            : /tmp/{{ template_file }}
    flat            : yes
    fail_on_missing : yes

- name     : template remote hosts
  template :
    src   : /tmp/{{ template_file }}
    dest  : {{ templated_file_dest }}
    owner : {{ templated_file_owner }}
    group : {{ templated_file_group }}
    mode  : {{ templated_file_mode }}

The fetch task uses run_once to make sure that it only bothers copying the template from the first host it runs against. Assuming all these hosts in your play are the getting the same repo then this should be fine but if you needed to make sure that it copied from a very specific host then you could combine it with delegate_to.

Alternatively you could just have Ansible clone the repo locally and use it directly with something like:

- name : clone repo on remote hosts
  git  :
    repo : {{ git_repo_src }}
    dest : {{ git_repo_dest }}

- name       : clone repo on Ansible host
  hosts      : localhost
  connection : local
  git  :
    repo : {{ git_repo_src }}
    dest : {{ git_repo_local_dest }}

- name     : template remote hosts
  template :
    src   : {{ template_local_src }}
    dest  : {{ templated_file_dest }}
    owner : {{ templated_file_owner }}
    group : {{ templated_file_group }}
    mode  : {{ templated_file_mode }}

Leave a Comment