Reputation: 6337
I want to check that only one of several Ansible variables is defined. It seems that Ansible conditions don't support xor. The best way I've found so far is something like this:
- fail:
msg: "var1 xor var2 xor var3 must be defined"
when: (var1 is defined | ternary(1, 0) + var2 is defined | ternary(1, 0) + var3 is defined | ternary(1, 0)) != 1
Dictionary version:
(item.get('key1') | ternary(1, 0) + item.get('key2') | ternary(1, 0) + thedict.get('key3') | ternary(1, 0)) != 1
Is there a simpler way?
Upvotes: 0
Views: 1420
Reputation: 68559
This should count as simpler:
- fail:
msg: "only one of var1, var2, or var3 must be defined"
when: checklist | select() | list | length != 1
vars:
checklist:
- "{{ var1 is defined }}"
- "{{ var2 is defined }}"
- "{{ var3 is defined }}"
Upvotes: 3
Reputation: 68134
As of Ansible 2.6 there isn't simpler way IMHO. To test list of conditions (see Group theory tests) there is only AND (list is all) and OR (list is any).
Upvotes: 0