Why do variables for a template need top be defined 'above' the template task?

I want to use ansible.builtin.template. So I tried as a task:

- name: Create cfg file
  ansible.builtin.template:
    src: path/to/my/template.j2
    dest: /path/to/output/file.conf
    vars:
      my_port: 1234

with the file template.j2 containing somewhere

port = {{ my_port }}

This task does not work. It has no syntax error, but at run time it complains about my_port not beeing defined.

Moving the variable to the block ‘above’ works:

- name: Create cfg file
    vars:
      my_port: 1234
    block:

    - name: Use template
      ansible.builtin.template:
        src: path/to/my/template.j2
        dest: /path/to/output/file.conf

Why is that?

Thanks for any explanation!

Is it a mistake with whitespace, try this?

- name: Create cfg file
  ansible.builtin.template:
    src: path/to/my/template.j2
    dest: /path/to/output/file.conf
  vars:
    my_port: 1234
1 Like

@chris gave you the riight syntax, for your task. However, I just want to just supplement their answer. “vars” is not an attribte of the template module. If you look at the template module here:
ansible.builtin.template module – Template a file out to a target host — Ansible Community Documentation. You will see “vars” is not a valid attribute you can use. However, “vars” is a valid attribute you can use at the task or block level.

# Valid for block
- name: my block
  vars:
     redfish: bluefish


# valid for task
- name: my task
  vars:
     redfiish: bluefish
  ansiblemodule:  jasldasjfdlaj

# invalid for task
- name: my task
  ansiblemodule:
      vars:
         redfish: bluefish

2 Likes

Variables are ansible core feature, it allows you to create re-usable/configurable blocks of automation.

They can also control how ansible connects/acts with your targets.

To learn more about variables, see the docs.

1 Like

Thanks @chris! That was it.

I had thought of the vars at part of (common?) attributes to the module, but, as @binbashroot points out, they are not.

Also, I wasn’t aware that vars can be attached to any name section, i.e. can be attached to a task.