Is it possible to use jinja2 templates in tasks?

Hi! I’m trying to implement firewall rules management with ufw module. Idea is to have list of ports to be accessable from sources somewhere in host variables. For example, I have this in my group_vars/consul_servers:

ufw_open_docker_from_sources:
  - {port: 8500, src: consul_agents}
  - {port: 8301, src: consul_agents}

Where consul_agents is a group name.

And I have a firewall/main.yml in my rules, where I’m trying to expand this list of ports and groups into some tasks:

{% for item in hostvars['ufw_open_docker_from_sources'] %}
{% for host in groups[item.src] %}
- name: Enable access to some docker ports from particular source
  ufw:
    insert=1
    route=yes
    rule=allow
    port={{ item.port }}
    src={{ hostvars[host]['ip'] }}
{% endfor %}
{% endfor %}

But this does not work because of error:

ERROR! Syntax Error while loading YAML.

The error appears to have been in '/Users/art/projects/ansible/with-roles/roles/firewall/tasks/main.yml': line 25, column 2, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

{% for item in hostvars['ufw_open_docker_from_sources'] %}
 ^ here

Is it possible to overcome this limitation?

no, you cannot use jinja to generate tasks on the fly.

you should look into the different lookups as you can combine them to
create what you need in a single task.

I see. I found a workaround using with_subelements:

Now I have:

`
ufw_open_docker_from_sources:

  • {port: 8500, src: “{{ groups.all_consuls }}”}
  • {port: 8301, src: “{{ groups.all_consuls }}”}
    `

in my group_vars file. This way, I have all hosts from the group as a list in my src attribute.

And this piece in my tasks:

`

  • name: Enable access to some docker ports from particular source
    ufw:
    insert=1
    route=yes
    rule=allow
    port={{ item.0.port }}
    src={{ hostvars[item.1][‘ip’] }}
    with_subelements:
  • ufw_open_docker_from_sources
  • src

`

This generates a one rule for each host, as desired.