Shruti
Shruti

Reputation: 131

AnsibleError: template error while templating string: expected token 'end of print statement', got '{'

The following is a task, which is throwing me an error because jinja2 templating doesnt support this.

- name: Print the ip address
  debug:
    msg: "{{ ansible_{{ item }}['ipv4']['address'] }}"
  with_items: "{{ ansible_interfaces|reject('search', 'lo')|list|sort }}"

The error thrown is:

"msg": "template error while templating string: expected token 'end of print statement', got '{'. String: {{ ansible_{{ item }}['ipv4']['address'] }}"

Any pointers on how to solve this issue?

Upvotes: 9

Views: 29308

Answers (2)

Zeitounator
Zeitounator

Reputation: 44635

You cannot use jinja2 expansion when you are already inside a jinja2 expansion expression. In other words mustaches don't stack.

In your case you can use the vars lookup to fetch your dynamically named var:

- name: Print the ip address
  vars:
    interface_var_name: "ansible_{{ item }}"
  debug:
    msg: "{{ lookup('vars', interface_var_name)['ipv4']['address'] }}"
  with_items: "{{ ansible_interfaces | reject('search', 'lo') | list | sort }}"

Upvotes: 6

Vladimir Botka
Vladimir Botka

Reputation: 68074

Use lookup plugin vars. For example

    - name: Print the ip address
      debug:
        msg: "{{ my_ifc.ipv4.address|default('Undefined') }}"
      loop: "{{ ansible_interfaces|reject('search', 'lo')|list|sort }}"
      vars:
        my_ifc: "{{ lookup('vars', 'ansible_' ~ item) }}"

gives

ok: [localhost] => (item=eth0) => 
  msg: 10.1.0.27
ok: [localhost] => (item=wlan0) => 
  msg: Undefined

Upvotes: 3

Related Questions