Ansible inventory: aws_ec2 module -- Looking for an example of a working 'groups:' function

Viewed 745

I have a dynamic ansible inventory which uses the aws_ec2 module. It works quite well, generally. However, there is one issue. I've tried several times to create groups using the 'groups:' keyword, and all attempts have failed. The documentation is a little sparse -- in fact here it is, in its entirety:

groups: (dictionary)
Default:{}
Add hosts to group based on Jinja2 conditionals.

I've tried a number of syntaxes, Jinja2, conditionals, declarations, and so far none have succeeded in creating a group named 'foo'. For awhile I thought maybe I need to pass a small code snibbet that returns true or false, and thus include or exclude the targeted hosts. This doesn't seem to be the case. I'm wondering if anyone here has used the 'groups:' keyword and gotten further than I have. I found very little while Googling. FWIW, I am using ansible 2.9.9 on Linux.

Some examples of things that don't work:

---
plugin: aws_ec2

### fails to create a group
groups:
  foo: >-
    tags.get('Name') if tags.get('Name') == 'foo-server'

### returns every host in the AWS account. 
groups: 
  bar:
    - "{{ tags.get('Name') == 'bar-server' }}"

Also, it is difficult to use ansible's debugging tools with this module. Many, like the playbook debugger, seem not to work properly, though I find them quite useful in other contexts. Any tips you might have for debugging in this context would be warmly appreciated.

1 Answers

It looks like you were very close

As with many things ansible, the authoritative "documentation" is the source code. Specifically their use of the 'groups' option which calls _add_host_to_composed_groups wherein they feed the groups: dict into a Jinja2 evaluation context containing all the hostvars. The expression is plugged into {% if ... %} so you wouldn't want to include the {{ markers in your expression, just the "raw" jinja2 expression

groups:
  foo: tags.get('Name') == 'foo-server'

Be forewarned that I don't have an environment handy to test that inventory script, but that's the theory

Related