Looking for a script to save the state of lights and revert after action

I’m trying to avoid re-inventing the wheel here. I have a script which uses lights around the house to signal various alerts by flashing in a relevant colour. At the end of the script, I revert the lights to white and then switch them off. I do this by controlling the group to which the lights belong.

In practice, though, not all lights will have been either white or off before the process started.

What I need, ideally, is something which parses the group membership, records the state of each and saves it so that I can then revert each to its original state, rather than assuming white and off.

I’m sure that this must be a fairly common requirement? If someone could point me in the right direction, I’d be most appreciative.

TIA

Example from

# Example automation using snapshot
- alias: "Window opened"
  trigger:
  - platform: state
    entity_id: binary_sensor.window
    from: "off"
    to: "on"
  condition: []
  action:
  - service: scene.create
    data:
      scene_id: before
      snapshot_entities:
      - climate.ecobee
      - light.ceiling_lights
  - service: light.turn_off
    target:
      entity_id: light.ceiling_lights
  - service: climate.set_hvac_mode
    target:
      entity_id: climate.ecobee
    data:
      hvac_mode: "off"
- alias: "Window closed"
  trigger:
  - platform: state
    entity_id: binary_sensor.window
    from: "on"
    to: "off"
  condition: []
  action:
  - service: scene.turn_on
    target:
      entity_id: scene.before

Fantastic! thank you very much

Temporary scenes can be a great way of doing it.
For a simpler use case, you could just grab the state of the entity before you act on it and save its value into a variable such as:

variables:
  previous_switch_state: "{{ states('switch.aqara_switch_top_floor_bathroom_switch') }}"

Then, perform the action on your entity, then restore its state back to the previous value. This is fine where you have a simple entity like a switch, but for lights, where you might want to capture many attributes of that device, such as colour, brightness etc, then temporary scenes are really the way to go.

Oooh! that might be cleaner still. I just need to find a way to iterate it through all of the group members.

Thanks,