Reputation: 45
i hope you guys can help me. I want to copy following template with ansible:
IFACE_EXTERNAL="{{ ansible_default_ipv4.interface }}"
IP_EXTERNAL="{{ ansible_default_ipv4.address }}"
IFACE6_EXTERNAL="{{ ansible_default_ipv6.interface }}"
IP6_EXTERNAL="{{ ansible_default_ipv6.address }}"
{% if ansible_interfaces[2] is defined %}
{% set count = 2 %}
{% for iface in ansible_interfaces %}
{% if "tun0" in iface %}
IFACE_INTERNAL_1="{{ iface }}"
{% endif %}
{% if "ens" in iface %}
IFACE_INTERNAL_{{count}}="{{ iface }}"
{% set count = count + 1 %}
{% endif %}
{% if hostvars[inventory_hostname]['ansible_%s'|format(iface)]['ipv4'] is defined %}
IP_INTERNAL_{{loop.index}}="{{ hostvars[inventory_hostname]['ansible_%s'|format(iface)]['ipv4']['address'] }}"
{% endif %}
{% endfor %}
{% endif %}
Now, if i copy this template with ansible, i get following error: "AnsibleUndefinedVariable: 'dict object' has no attribute 'interface'". I tried for an hour but don't get a solution. Does anyone know where the error is?
Upvotes: 0
Views: 1902
Reputation: 170798
To avoid such errors you must use something similar to {{ ansible_default_ipv6.interface | default('foo') }}
as there is no guarantee that ansible_default_ipv6 object has the interface attribute.
If you do not do this, you will get templating errors. The other option is to use if conditions like '{% if interface' in ansible_default_ipv6 %}...
.
Upvotes: 1
Reputation: 7917
You wrote a very complicated jinja template. Now, live and suffer with it.
It's really bad idea to have a complicated access patterns into dynamic variables within jinja, as you have 0 (zero) debug tools there.
The proper way is to have all computation to be done at ansible level:
tasks:
- debug: var=some_var1
- debug: var=some_var2
- template:
src: foo.j2
dest: foo
vars:
some_var1: '{{...}}'
some_var2: '{{...}}'
By using external (ansible) vars you can debug them. If you use computation in Jinja you need to be 100% sure data are there. How can you be sure that facts are there, if default
set of network variables is dependent on where there is default gateway or not on the target system?
Upvotes: 1