How do I use repeat for_each in a script and iterate through all entities in a domain?

I’m trying to write a script that uses repeat for_each to iterate through all entities of the domain “timer” but googling and trying for 30 minutes left me with nothing. I can easily write something in developer tools → template that will list the desired entities, but this won’t work with for_each.

When nailing that, I intend to pause timers that have less than 5 mins left or unpause paused timers. Reason for this is to keep timers from finishing while HA restarts.

I do not think the state of timers are carried over through a restart.
The timers will be reset on start up.
You might need to use timestamps instead.

Timers are preserved through restarts as long as the timer doesn’t finish while HA is down (which is what OP is trying to prevent)

ok, nice to know. :slight_smile:

I recall an issue while trying to create a helper that contained a list of WiFi devices on my network. I’m sorry I can’t remember the explanation in perfect detail but the gist of it was that the output of the list template function didn’t output the list in a JSON compatible format?

I think I had to use replace functions to replace double quotes (") with single quotes (') and use the to_json function to convert the array into a JSON compatible one? That list could then be parsed correctly.

Unfortunately I ended up just calling the template directly in a markdown card rather than saving it in a helper so the template I had for converting all items in the device_tracker domain to a JSON list is long gone. I will have a look around the forums and see if I can find anything related to it, but hopefully this will push you in the right direction or others might add onto this.

You don’t need a foreach

- variables:
    less_than_five: >
      {% set t = (utcnow() + timedelta(minutes=5)).isoformat() %}
      {{ states.timer | selectattr('state', 'eq', 'active') | selectattr('attributes.finishes_at', '<', t) | map(attribute='entity_id') | list }}
- if: "{{ less_than_five | count > 0 }}"
  - service: timer.pause
      entity_id: "{{ less_than_five }}"

I prefer your solution to my convoluted BS :laughing:

That’s a very elegant solution indeed! Thanks! I wasn’t thinking outside the scope of using for_each.