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

1

8

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.

Deen answered 31/5, 2020 at 2:13 Comment(0)
H
12

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

Hoskins answered 1/6, 2020 at 0:46 Comment(6)
Ah! Thank you, mdaniel! This was just the breakthrough I needed. Cheers --Deen
I'm glad it worked for you; please consider accepting the answer to let others know it solved your problemHoskins
You might also have to wrap it in a set of exterior quotes: foo: "tags.get('Name') == 'foo-server'"Musso
@JoshK only if the expression contains yaml sensitive characters, which that expression does not; I try very hard to execute any answer that I post in order to catch things like thatHoskins
This works, but it's pretty slow - it takes 16 seconds whereas if I just filter by the tagname without creating groups then it takes 1 second.Aetna
tags.get('Name').startswith('myPrefix') helped me hereMulley

© 2022 - 2024 — McMap. All rights reserved.