--- - name: Run DC patch task via JEA-PatchOps hosts: domain_controllers gather_facts: no vars: task_path: '\\' # e.g. '\\Microsoft\\Windows\\WindowsUpdate\\' task_name: 'Patching-windows-task' poll_delay: 60 poll_retries: 3 # up to 6h tasks: - name: Ensure the task is enabled (in case it was disabled) ansible.windows.win_powershell: script: | Import-Module ScheduledTasks $tp='{{ task_path }}'; $tn='{{ task_name }}' $t = Get-ScheduledTask -TaskPath $tp -TaskName $tn if ($t.Settings.Enabled -ne $true) { Enable-ScheduledTask -TaskPath $tp -TaskName $tn } changed_when: "'Enable-ScheduledTask' in (result.stdout | default(''))" register: result failed_when: false - name: Start the SYSTEM patch task (schtasks) ansible.windows.win_command: > schtasks /Run /TN "{{ task_path }}{{ task_name }}" register: start_task failed_when: false changed_when: > (start_task.rc | default(1)) == 0 or ('SUCCESS' in (start_task.stdout | default(''))) - name: Poll until task is Ready/Disabled with success ansible.windows.win_powershell: script: | $ErrorActionPreference = 'Stop' Import-Module ScheduledTasks $tp='{{ task_path }}'; $tn='{{ task_name }}' $i = Get-ScheduledTaskInfo -TaskPath $tp -TaskName $tn [PSCustomObject]@{ State=$i.State; LastTaskResult=$i.LastTaskResult } | ConvertTo-Json -Compress register: task_info failed_when: false retries: "{{ poll_retries }}" delay: "{{ poll_delay }}" until: > (task_info.stdout | default('') | length > 0) and ((task_info.stdout | from_json).State in ['Ready','Disabled']) and (((task_info.stdout | from_json).LastTaskResult | int) == 0) - name: Reboot if needed (belt & suspenders) ansible.windows.win_reboot: reboot_timeout: 5400 when: (task_info.stdout | from_json).State == 'Ready'