I created https://github.com/eparis/ansible-inventory-bug to show exactly what I mean with a clean reproducer which anyone can run locally. It has both a 'dynamic' inventory and a static inventory.
(For 'dynamic' it really is just catting in some json, but it shows the problem clearly)
With a static inventory file when: inventory_hostname in {{ groups['group'] }}
works just fine. But with dynamic inventory it fails with what looks like some python localization/string handling mess...
So just did a lot of experimenting and found
Works:
when: inventory_hostname in groups['group']
Fails:
when: inventory_hostname in {{ groups['group'] }}
So it is the extra set of {{ }} that causes the problem. Although I don't know why it works for static but not for dynamic.
You should not use {{ }} in when (we should actually make this an error), the reason that the static/dynamic works a bit differently here seems to be because of the type of object returned in the end, list vs unicode string.
closing as per above
Most helpful comment
So just did a lot of experimenting and found
Works:
when: inventory_hostname in groups['group']
Fails:
when: inventory_hostname in {{ groups['group'] }}
So it is the extra set of {{ }} that causes the problem. Although I don't know why it works for static but not for dynamic.