--- - name: "Maintenance | Start stopped automatic services" hosts: all gather_facts: true tasks: - name: "Windows | Start stopped automatic services" when: ansible_facts['os_family'] == 'Windows' ansible.windows.win_powershell: script: | $Ansible.Changed = $false $started = @() Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -ne 'Running' } | ForEach-Object { try { Start-Service -Name $_.Name -ErrorAction Stop $started += $_.Name $Ansible.Changed = $true } catch { Write-Warning "Could not start service $($_.Name): $($_.Exception.Message)" } } $Ansible.Result = @{ started_services = $started } register: started_services_windows - name: "Windows | Show started services" when: ansible_facts['os_family'] == 'Windows' ansible.builtin.debug: var: started_services_windows.result.started_services - name: "Linux | Collect service facts" when: ansible_facts['os_family'] != 'Windows' ansible.builtin.service_facts: - name: "Linux | Start stopped enabled systemd services" when: - ansible_facts['os_family'] != 'Windows' - ansible_facts['service_mgr'] == 'systemd' - item.value.status | default('') == 'enabled' - item.value.state | default('') != 'running' become: true ansible.builtin.systemd: name: "{{ item.key }}" state: started loop: "{{ ansible_facts.services | dict2items }}" loop_control: label: "{{ item.key }}" register: started_services_linux failed_when: false - name: "Linux | Show services that were started" when: - ansible_facts['os_family'] != 'Windows' - ansible_facts['service_mgr'] == 'systemd' ansible.builtin.debug: msg: >- {{ started_services_linux.results | default([]) | selectattr('changed', 'defined') | selectattr('changed') | map(attribute='item.key') | list }} - name: "Linux | Report unsupported service manager" when: - ansible_facts['os_family'] != 'Windows' - ansible_facts['service_mgr'] != 'systemd' ansible.builtin.debug: msg: >- Automatic stopped-service recovery currently supports systemd hosts only. Detected service manager: {{ ansible_facts['service_mgr'] }}