default for undefined dict

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

FYI :
ansible 2.2.0.0

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

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 %}

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.