--- - name: Run DC patch task via SYSTEM scheduled task hosts: domain_controllers gather_facts: no vars: task_path: "\" # e.g. "\" or "\Microsoft\Windows\WindowsUpdate\" task_name: "Patching-windows-task" tasks: - name: Start the SYSTEM patch task ansible.windows.win_command: > schtasks /Run /TN "{{ task_path }}{{ task_name }}" register: start_task changed_when: start_task.rc == 0 failed_when: start_task.rc not in [0] and ("SUCCESS" not in (start_task.stdout | default(''))) - name: Poll task until it is Ready or Disabled ansible.windows.win_powershell: script: | $ErrorActionPreference = 'Stop' Import-Module ScheduledTasks $tp = '{{ task_path }}' $tn = '{{ task_name }}' # Confirm it exists (throws if not) $null = Get-ScheduledTask -TaskPath $tp -TaskName $tn $state = (Get-ScheduledTaskInfo -TaskPath $tp -TaskName $tn).State # Return plain text state for Ansible to parse $state register: task_state failed_when: false retries: 3 # up to 3 hours delay: 60 until: task_state.stdout | trim in ['Ready','Disabled'] - name: Show last observed task state (debug) ansible.builtin.debug: msg: - "Task '{{ task_path }}{{ task_name }}' final state: {{ task_state.stdout | trim }}" - name: Reboot if needed ansible.windows.win_reboot: reboot_timeout: 3600 when: task_state.stdout | trim == 'Ready'