Hi,
I’m trying to organize my inventory variables, and I’m struggling with the syntax.
I have an inventory structure similar to one suggested in documentation :
admin@ansible:~/ansible/environments$ find .
.
./000_cross_env_vars.yml
./prod
./prod/group_vars
./prod/group_vars/all
./prod/group_vars/all/000_cross_env_vars
./prod/group_vars/all/001_env_specific.yml
./prod/hosts
./prod/host_vars
./prod/host_vars/host-a.yml
./prod/host_vars/host-b.yml
./staging
./staging/group_vars
./staging/group_vars/all
./staging/group_vars/all/000_cross_env_vars
./staging/group_vars/all/001_env_specific.yml
./staging/hosts
In my 001_env_specific.yml file, I define a list of hosts/networks/ports that I will use to setup my firewalling rules using UFW (servers are running Ubuntu 22.04). Then I have some rules defined in host_vars, that use variables defined in group_vars.
Example group_vars :
# Hosts
ufw_host_bastion: 192.168.1.2
# Networks
ufw_net_postes_adm:
- 192.168.10.0/24
- 192.168.20.0/24
Example host_vars :
ufw_rules:
- rule: allow
from_ip: "{{ ufw_host_bastion }}"
to_port: "{{ ufw_port_ssh }}"
protocol: tcp
interface: "{{ if_adm }}"
comment: 'allow incoming ssh on admin interface from bastion'
{%- for item in ufw_net_postes_adm -%}
- rule: allow
from_ip: {{ item }}
to_port: {{ ufw_port_https }}
protocol: tcp
interface: {{ if_adm }}
comment: 'allow incoming HTTPS on admin interface from admin network {{ item }}'
{%- endfor -%}"
This fails with the following message :
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
found character that cannot start any token
The error appears to be in '/home/admin/ansible/environments/prod/host_vars/host-a.yml': line 14, column 2, but may be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
{%- for item in ufw_net_postes_adm -%}
^ here
I searched Ansible’s documentation if there are restrictions on how I can use Jinja2 inside variable files, but found nothing. It seems I can only use {{ variable }}
inside inventory files but no {% %}
instruction.
How can I achieve this in a correct syntax way ?