NemoSaltatSobrius
NemoSaltatSobrius

Reputation: 41

Is it possible to use variable in Jinja2 default filter?

I guess it is not possible to refer to item variable when using Jinja2 'default' filter?

Like in this example playbook:

---
- hosts: localhost
  become: no
  gather_facts: no

  vars:
    users:
      - foo:
        name: "foo"
        home: /home/foo
      - bar:
        name: "bar"

  tasks:

    - name: debug
      debug:
        msg: "{{ item.home | default('/home/{{ item.name }}') }}"
      loop: "{{ users }}"

If tried I get output like:

$ ansible-playbook test.yml |grep item
ok: [localhost] => (item={u'home': u'/home/foo', u'foo': None, u'name': u'foo'}) => {
ok: [localhost] => (item={u'bar': None, u'name': u'bar'}) => {
    "msg": "/home/{{ item.name }}"

Obviously I want "/home/bar" not "/home/{{ item.name }}".

Upvotes: 2

Views: 617

Answers (1)

nwinkler
nwinkler

Reputation: 54437

Just use string concatenation in the expression, don't use nested handlebars...

"{{ item.home | default('/home/' + item.name) }}"

This adds the item.name variable to the static /home part.

Upvotes: 5

Related Questions