I spent a long time trying to get this to work, and eventually managed it, so just in case it's useful for anyone else...
I wanted to tag my EC2 instances with, say 'webserver: True' and have them then appear in the 'webserver' host group locally, but I wanted to do it as a general case, without having to write special code for every group.
The ec2.py inventory script will put each host into a group called 'ec2' and also, for example, into 'tag_webserver_True'.
So this is what I did next:
- name: Add hosts in EC2 tag groups to local groups
name={{inventory_hostname}}
when: item.startswith('tag_') and item.endswith('_True') and (inventory_hostname in groups[item])
It took me a couple of hours playing with all sorts of variations on this theme to realise that the really important bit is to include 'serial: 1'.
Adding things to groups using add_host does not work reliably if there are multiple hosts being processed simultaneously. You will probably find that a single host gets added to the group but no more.
This, however, seems to work fine, and can easily be included in playbooks where it will be ignored if you're not using any EC2 hosts.
Hope that's useful for someone!