2

How do we do a wildcard search with Ansible nested variable?

YAML

test:
  name:
    address:
         zipcode: 12345

Ansible Template Variable

{{ test[name][addre*].zipcode }}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Amala
  • 161
  • 1
  • 3
  • 13

1 Answers1

6

How do we do a wildcard search with Ansible nested variable?

- debug:
    msg: >-
      {{ test.name
      | dict2items
      | selectattr("key", "match", "addr.*")
      | map(attribute="value.zipcode")
      | list }}

Where dict2items explodes the children of name allowing one to pattern match -- or any other fun tricks -- based on the key of the dict, which ordinarily -- as you have seen -- isn't possible

Then we now have a list of matching {"key": "address1234", "value": {"zipcode": "11111"}} structures, so if you want the zipcode field of all of them, just reach into the value dict and pull out its zipcode field.

The final list is a concession because map produces a python generator, and not an actual list

mdaniel
  • 31,240
  • 5
  • 55
  • 58