Correct way to create dynamic lists in Ansible


I’m looking for advice. I have the following code that creates a list dynamically that I can then later use in a template.

This is a copy of the test code I put together – for the actual role I just added the admins|regex_replace variable into the j2 template.

This gives me the following:

So…I get what I need, but am I going about it the right way?

Ansible version is running on Centos 7.2.

Thanks in advance.

Edit: The resultant filter ended up looking like this:

Having added another parameter to the yaml:

Ringo was left out, as desired.


Filters will operate on lists, so the with_items is really wasteful, and the regex stuff is pretty obtuse for what you’re doing. Do you really want a comma-separated string, or do you just want a list of the usernames extracted from the admin_accounts list?

If you just want the list, why not:

… and if you really want the comma-separated list as a flat string, just add a join filter:

If your ultimate target is a template, though, I’d suggest doing this inside the template, since this looks pretty formatting-related as opposed to logic-related (unless you’re just simplifying for Stack Overflow purposes)…

Leave a Reply