Conditionally updating a list?

So, I’m looking for a way to add items to a list conditionally. The point of the list is to be provided for a with_items clause. I know I can evaluate python in jinja expressions, but it seems that those changes may be localized to the expression where they are evaluated.

Here’s a general idea of what I’m attempting to do. I have tested this playbook, and the output at the end is “foo”, “bar”, “baz”, with “harpo” and “groucho” nowhere to be found, and yes, I’ve verified that enable_harpo and enable_groucho evaluate to true.

There’s no way to dynamically append to a list presently.

Since you’ve shared an abstract example, it might be a good idea to explain the use case and we can share some other ways to model it?

Well,
In this case, I have a set of services, each of which needs to have some operations applied to them (the same operations across all services). The use case really is what you see in the abstract example; there are times when some of the services have not been enabled, and if they are enabled, I need to perform the task on them, if not, I don’t. I’ve already got the service operations abstracted out to an ansible task, so instead of dynamically altering the list, I can simply “include” the task again if the service is enabled. Updating a list and using with_items one time simply felt much cleaner… if it could have been done.

Perhaps you could do something like this:

  • name: update the stuff
    when: services[name].enabled
    with_items: service_names

It sounds like you are driving this from inventory and not the state of the current system but it’s not clear to me from the above.

I am driving it from inventory. That’s actually a good call, adding an “_enable” value for every service, including the services which are never disabled. Thanks!