Ansible selectattr and map with optional fields

Viewed 246

I am trying create an ansible playbook to set up multiple nodes. In my variables I have a the following structure:

nodes:
  - nodename: foonode
    othervalue: foo
    booleanvalue: true
  - nodename: barnode
    othervalue: bar

The booleanvalue is optional and shoutd default to false. Later it might be possible to have more optional values. For now I only want to use the optional boolean value.

- name: "Debug"
  debug:
    msg: "Do something useful here"
  when:  when: nodes | selectattr('nodename', 'equalto', ansible_hostname) | map(attribute='booleanvalue') | first | bool

This code snippet works as long as booleanvalue exists. But it does not work for barnode. As I am using 2.9.6 I cannot use map(attribute='booleanvalue', default='whatever'). Is there another or better way to make it work with optional values?

1 Answers

Put the data into a dictionary. For example,

nodes:
  foonode:
    othervalue: foo
    booleanvalue: true
  barnode:
    othervalue: bar

Then, the condition is trivial

  - debug:
      msg: "Do something useful here"
    when: nodes[inventory_hostname]['booleanvalue'] | default(false)

not tested

Related