default for undefined dict

29 views
Skip to first unread message

adrien nayrat

unread,
Feb 8, 2017, 5:29:58 AM2/8/17
to Ansible Project
Hi,



Here is my variable :

instances:
  - name: ref
    mgservices:
      name: test1


My default variable:

default_mgservice :
  name: blah

I want to use "default_mgservice.name" when mgservices is not defined :
instances:
  - name: ref

Here is my template

{% for instance in instances %}
pgservice : {{ instance.mgservices.name | default(default_mgservice.name) }}
{% endfor %}

But it failed :

"AnsibleUndefinedVariable: 'dict object' has no attribute 'mgservices'"}

I don't understand why default do not work on dict? Any idea?

Thanks

adrien nayrat

unread,
Feb 8, 2017, 5:34:18 AM2/8/17
to Ansible Project

FYI :
ansible 2.2.0.0

Johannes Kastl

unread,
Feb 8, 2017, 5:42:04 AM2/8/17
to ansible...@googlegroups.com
On 08.02.17 11:29 adrien nayrat wrote:

> instances:
> - name: ref
> mgservices:
> name: test1

> pgservice : {{ instance.mgservices.name |

> "AnsibleUndefinedVariable: 'dict object' has no attribute 'mgservices'"}

Just a guess:
Your problem is not the default, but rather how you try to address
your dict.

Try this:
pgservice: {{ instance["msgservices"]["name"] }}

Johannes

signature.asc

adrien nayrat

unread,
Feb 8, 2017, 6:37:24 AM2/8/17
to Ansible Project

Just a guess:
Your problem is not the default, but rather how you try to address
your dict.

Try this:
pgservice: {{ instance["msgservices"]["name"] }}

Johannes

Thanks but I have the same error. I want to use  default_mgservice.name when mgservices is not defined.

I find this workarround :
{% if instance.mgservices is defined %}
pgservice : {{ instance.mgservices.name | default(default_mgservice.name) }}
{% else %}
pgservice : {{ default_mgservice.name }}
{% endif %}

Stankovic, Marko

unread,
Feb 8, 2017, 6:42:34 AM2/8/17
to Ansible Project
Hi,

Try with this:
{% for instance in instances %}
pgservice : {{ (instance['mgservices'] | default(default_mgservice))['name'] }}
{% endfor %}

Cheers,
Marko
CONFIDENTIALITY NOTICE: This message is the property of International Game Technology PLC and/or its subsidiaries and may contain proprietary, confidential or trade secret information. This message is intended solely for the use of the addressee. If you are not the intended recipient and have received this message in error, please delete this message from your system. Any unauthorized reading, distribution, copying, or other use of this message or its attachments is strictly prohibited.
Reply all
Reply to author
Forward
0 new messages