2

I have a dictionary structure that I'm including in my role execution and I'm trying to set an item in one of the dictionaries based on another value. What happens in the below example would be that the execution will fail when running on "another_host" because it won't have the value called "value2" in the dictionary, Ansible gives the "'dict object' has no attribute" error.

I'm not sure if it's because I'm trying to do something that conflicts with Ansible's design or there's just a much simpler way to accomplish what I'm trying to do.

dict1:
  abc:
    name: abc
    value: something
  xyz:
    name: xyz
    value: "{{ dict2[inventory_hostname].values.value2 | default(blah) }}"

dict2:
  some_host:
    values:
      value1: aaa
      value2: bbb
  another_host:
    values:
      value1: aaa
techraf
  • 64,883
  • 27
  • 193
  • 198
Vadimski
  • 43
  • 3

1 Answers1

0

I've answered similar question here.

First of all, avoid using values names for dict keys, because it is a system "keyword". In your example you try to access value2 property of values() system method, this will definitely fail.

Second, |default('def') construction works fine if you have top-level variable undefined (dict2 in your example) or bottom-level key is undefined (value2 in your example). So, having no value2 is fine.

But if you have middle-level key undefined, like:

top:
  middle1:
    leaf1: 1
  middle3:
    leaf3: 3

top.middle2.leaf2 | default('def') will rise an error. In this case, defaulting every level to empty dict {} does the job: ((top | default({})).middle2 | default({})).leaf2 | default('def').

Community
  • 1
  • 1
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Thanks for the answer. It's still not working for me, and I think I'm missing something with the syntax inside the YAML. I have something like this: `something: "{{ dict1[inventory_hostname].leaf1.leaf2.leaf3 }}"` So do I need to add defaults to ALL of them? and if so where do I use parentheses and where are they not needed? – Vadimski Jan 31 '17 at 11:45